简体   繁体   English

在LINQ中使用不重复,其中涉及> 1列

[英]Using distinct in LINQ where >1 column involved

I have a list of records, 3 of the properties of which are 我有一个记录列表,其中3个属性是

VendorId
VendorName
VendorDesc

There could be multiple instances of the same vendor. 同一供应商可能有多个实例。

What I wish to do is retrieve a "distinct" list of "VendorNames" with the VenderDesc property as well. 我想做的是同时使用VenderDesc属性检索“ VendorNames”的“不同”列表。

Returning one property is fine ie 归还一项财产是可以的

var myVendorNameList = myRecords.Select(r=>r.VendorName).Distinct();

However I wish to add the VendorDesc to this list after which I interate through to output(Razor View) the content using foreach ie 但是我希望将VendorDesc添加到此列表中,然后使用foreach进行交互以输出(Razor View)内容

foreach (var item in myVendors)
{
 Name: @item.VendorName 
 Desc: @item.VendorDesc 
}

Thanks in advance. 提前致谢。

The simplest way is to GroupBy the field you want and decide which of the duplicate records you want: 最简单的方法是GroupBy你想要的领域,决定要重复的哪些记录:

myRecords.GroupBy(r=>r.VendorName)
         .Select(g => g.First());

您可以使用GroupBy 。这也将返回VendorId属性,但我认为这不是问题。

myRecords.GroupBy(x => x.VendorName).Select(g => g.First());

I think, using the morelinq's DistinctBy (as LB mentioned) or creating your own one would be more readable 我认为,使用morelinq的 DistinctBy(如LB所述)或创建自己的一个将更具可读性

public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source, 
                                                 Func<T, TKey> keySelector)
{
    HashSet<TKey> keys = new HashSet<TKey>();
    return source.Where(x => keys.Add(keySelector(x)));
}

You can now use it as 您现在可以将其用作

myVendorNameList  = myRecords.DistinctBy(r=>r.VendorName);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM