使用Linq删除重复项

时间:2012-05-16 05:11:19

标签: c# linq c#-4.0

我正在使用返回重复ID的API。我需要使用EF将这些值插入到我的数据库中。在尝试添加对象之前,我想要删除任何重复项。

我有一个我想写的代码的小例子。

  var itemsToImport = new List<Item>(){};
        itemsToImport.Add(new Item() { Description = "D-0", Id = 0 });            
        for (int i = 0; i < 5; i++)
        {
            itemsToImport.Add(new Item(){Id = i,Description = "D-"+i.ToString()});
        }

        var currentItems = new List<Item>
                        {
                            new Item() {Id = 1,Description = "D-1"},
                            new Item(){Id = 3,Description = "D-3"}
                        };
        //returns the correct missing Ids
        var missing = itemsToImport.Select(s => s.Id).Except(currentItems.Select(s => s.Id));


        //toAdd contains the duplicate record. 
        var toAdd = itemsToImport.Where(x => missing.Contains(x.Id));
        foreach (var item in toAdd)
        {
            Console.WriteLine(item.Description);
        }

我需要修改我的变量“toAdd”才能返回单个记录,即使有重复记录吗?

3 个答案:

答案 0 :(得分:3)

您可以通过按ID分组,然后选择每个组中的第一个项目来完成此操作。

var toAdd = itemsToImport
              .Where(x => missing.Contains(x.Id));

成为

var toAdd = itemsToImport
              .Where(x => missing.Contains(x.Id))
              .GroupBy(item => item.Id)
              .Select(grp => grp.First());

答案 1 :(得分:2)

使用MoreLINQ中的DistinctBy,如Jon Skeet在https://stackoverflow.com/a/2298230/385844

中所建议的那样

电话会看起来像这样:

var toAdd = itemsToImport.Where(x => missing.Contains(x.Id)).DistinctBy(x => x.Id);

如果您因某些原因而不愿意(或不能)使用MoreLINQ,那么DistinctBy很容易实现:

static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> sequence, Func<T, TKey> projection)
{
    var set = new HashSet<TKey>();
    foreach (var item in sequence)
        if (set.Add(projection(item)))
            yield return item;
}

答案 2 :(得分:0)

您可以使用Distinct功能。您需要覆盖Equals中的GetHashCodeItem(假设它们包含相同的数据)。

或者使用FirstOrDefault获取带有匹配ID的第一个项目。

itemsToImport.Where(x => missing.Contains(x.Id)).FirstOrDefault() 
相关问题