Question

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

i.e. 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?

Was it helpful?

Solution

By using MoreLinq you can use Distinct with lambda:

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top