简体   繁体   中英

Using distinct in LINQ where >1 column involved

I have a list of records, 3 of the properties of which are

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.

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

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:

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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