Reputation:
I apologize in advance if my terminology is off here, I'm still new to asp.net.
I have a model like this:
public class Order
{
public int FoodId { get; set; }
public int Amount { get; set; }
}
I have a list of orders, for which I want to create a copy which contains only one elment per FoodId. So if I have this:
1, 5
2, 3
1, 2
2, 6
3, 1
and I want to get a list like this:
1, 5
2, 3
3, 1
What is inside the amount doesn't matter to me, I just want to see a list of all unique FoodIds that exist in the first list. I would prefer to use a lambda function, like this (not real code, obviously):
List<Models.Order> FoodList = new List<Models.Order>(
OrderList.ForEach(o => FoodList.FindAll(if(o.FoodId not in Foodlist) return o))
);
Upvotes: 1
Views: 1234
Reputation: 306
You probably should use GroupBy
method, like this:
OrderList.GroupBy(x => x.FoodId).Select(g => g.First()).ToList();
Upvotes: 6
Reputation: 607
You can implement custom comparer
public class CustomComparer : IEqualityComparer<Order>
{
public bool Equals(Order x, Order y)
{
return x.FoodId == y.FoodId;
}
public int GetHashCode(Order obj)
{
return obj.FoodId.GetHashCode();
}
}
and pass it to Distinct() method
var newList = FoodList.Distinct(new CustomComparer()).ToList();
Upvotes: 0
Reputation: 3
you can use distinct() to solve this
like below
yourlist.Select(x => x.FoodId).Distinct();
Upvotes: 0