简体   繁体   中英

Find Distinct elements from a List C#

I have a class say named Product

public class Product
{
    public string Name{ get; set; }

    public int ProductId{ get; set; }

}

I have a list of Products, with same Name , but different ProductId .

I want to get distinct products from the list on product.Name

ie if the list is

var fullproductList = {
        Name: product,
        ProductId: 1
    }, {
        Name: product,
        ProductId: 2
    }, {
        Name: product,
        ProductId: 3
    };

I want any one the above product.

I want to achieve this without looping like this:

List<Product> distinctProducts= new List<Product>();

var distictproductName=fullSubjectList.Select(x => x.Name).Distinct().ToList();

foreach (var item in distictproductName)
{
    distinctProducts.Add(fullproductList.Where(x=>x.Name==item).FirstOrDefault());
}

Any suggestions?

通过使用MoreLinq ,可以将Distinct与lambda结合使用:

fullSubjectList.DistinctBy(x => x.Name).ToList();

Use linq with a group by on name. That will give you the distinct. Look at this answer for a few ideas : LINQ: Distinct values

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