user1734974
user1734974

Reputation:

Filter list: get only unique elements in objects

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

Answers (4)

You probably should use GroupBy method, like this:

OrderList.GroupBy(x => x.FoodId).Select(g => g.First()).ToList();

Upvotes: 6

Jack Sparrow
Jack Sparrow

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

Dipak Parekh
Dipak Parekh

Reputation: 3

you can use distinct() to solve this

like below

yourlist.Select(x => x.FoodId).Distinct();

Upvotes: 0

Markus
Markus

Reputation: 22456

If you are only interested in the unique food ids, you can first select them and use the Distinct method afterwards, e.g.:

OrderList.Select(x => x.FoodId).Distinct();

Upvotes: 2

Related Questions