By using MoreLinq
you can use Distinct
with lambda:
fullSubjectList.DistinctBy(x => x.Name).ToList();
Вопрос
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?
Решение
By using MoreLinq
you can use Distinct
with 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