如果List1包含的属性值等于Another List2的属性值,则检查List1

时间:2017-05-11 08:08:11

标签: c# linq

我有两个清单。

  1. 将插入数据库的新类别列表。
  2. 数据库中已存在的类别列表。
  3.     public class Category{ 
        public string Name;
        }
    
        list<Category> dbCategories = new List(new Category{Name="John"}, new Category{Name = "Daniel"}, new Category{Name = "Matthew"});  
    
    list<Category> newCategories = new List(new Category{Name="John"}, new Category{Name="Rock"}, new Category{"Daniel"});
    

    我想根据名称

    防止数据库中出现重复项

    我从数据库中获取类别列表。现在想检查要插入的新类别列表是否在数据库类别中具有匹配的名称。

    • 如果新类别在数据库类别列表中具有名称匹配,我想从要插入的新类别列表中删除该类别。
    • 我想检索一个匹配名称的项目,首先必须在第一个列表上进行搜索,如果没有找到匹配,则应搜索第二个列表。

    我如何实现这一目标?

2 个答案:

答案 0 :(得分:2)

您可以使用Where()Any()的组合,例如:

var newEntries = newCategories.Where(n => !dbCategories.Any(d => d.Name == n.Name));

否则,您可以考虑使用Except()使用IEqualityComparer重载来检查基于Name的相等性。

答案 1 :(得分:0)

最简单的方法是使用简单的反向for循环并删除类别列表中包含的每个项目。这是一个小程序来说明这一点:

void Main()
{
    List<string> categories = new List<string>() { "cat1", "cat2", "cat3" };
    List<string> tobeinserted = new List<string>() {"cat14", "cat2", "cat34"};

    for (int i = tobeinserted.Count-1; i >= 0 ; i--)
    {
        if (categories.Contains(tobeinserted[i]))
        {
            tobeinserted.RemoveAt(i);
        }
    }       
    Console.WriteLine(string.Join(Environment.NewLine, tobeinserted));      
}

输出是:

  

cat14
  cat34

要根据代码调整它,循环可能如下所示:

List<string> dbCategories_Names = dbCategories.Select(x => x.Name).ToList();

for (int i = newCategories.Count-1; i >= 0 ; i--)
{
    if (dbCategories_Names.Contains(newCategories[i].Name))
    {
        newCategories.RemoveAt(i);
    }
}