Linq select objects in list where exists IN (A,B,C)

前端 未结 5 1772
闹比i
闹比i 2020-11-28 04:05

I have a list of orders.
I want to select orders based on a set of order statuses.

So essentially select orders where order.Statu

5条回答
  •  难免孤独
    2020-11-28 04:13

    NB: this is LINQ to objects, I am not 100% sure if it work in LINQ to entities, and have no time to check it right now. In fact it isn't too difficult to translate it to x in [A, B, C] but you have to check for yourself.

    So, instead of Contains as a replacement of the ???? in your code you can use Any which is more LINQ-uish:

    // Filter the orders based on the order status
    var filteredOrders = from order in orders.Order
                         where new[] { "A", "B", "C" }.Any(s => s == order.StatusCode)
                         select order;
    

    It's the opposite to what you know from SQL this is why it is not so obvious.

    Of course, if you prefer fluent syntax here it is:

    var filteredOrders = orders.Order.Where(order => new[] {"A", "B", "C"}.Any(s => s == order.StatusCode));
    

    Here we again see one of the LINQ surprises (like Joda-speech which puts select at the end). However it is quite logical in this sense that it checks if at least one of the items (that is any) in a list (set, collection) matches a single value.

提交回复
热议问题