简体   繁体   English

从列表中获取对象 <object> 其中property为null且o​​rder为最低

[英]Get object from List<object> where property is null and order is the lowest

I have a class: 我有一节课:

public class Menu
{
    public Menu()
    {

    }

    public string Value { get; set; }
    public int Order { get; set; }
}

and then: 接着:

 List<Menu> menus = new List<Menu>() // contains 10 items let's say.

How can I get the item from the list where the Value == null and the Order is the smallest values among items? 如何从列表中获取Value == null且订单是项目中最小值的项目?

Example: 例:

Menu items can have an order like this: 10, 20, 30, 40, 50 ... 菜单项可以有这样的订单: 10, 20, 30, 40, 50 ...

There are no items with the same order, each item has a unique number value. 没有具有相同订单的商品,每个商品都有唯一的数字值。

I am interested to get the Menu when the Order is the smallest one and Value is null. 我有兴趣在订单最小的时候获取菜单,而值为空。 In this case the item where Order is 10 and Value null. 在这种情况下,Order为10且Value为null的项目。

Use Linq for that: 使用Linq:

 var result = menus.Where(x => x.Value == null).OrderBy(x => x.Order).FirstOrDefault();

Where takes only object with Value == null 只使用Value == null的对象

OrderBy orders them by Order property OrderBy通过Order属性对它们进行排序

FirstOrDefault takes first value or returns null if there are none that match the query 如果没有匹配查询的FirstOrDefault采用第一个值或返回null

 // This can be written in a shorter form
 var resultWithShorterLinq = menus.OrderBy(x => x.Order).FirstOrDefault(x => x.Value == null);

Both ways are equivalent, because with Linq you first build query with methods like Where, OrderBy, OrderByDescending... And only execute it when you call one of these methods: 两种方式都是等价的,因为使用Linq,您首先使用Where,OrderBy,OrderByDescending等方法构建查询...并且只有在调用以下方法之一时才执行它:

query.ToList();
query.ToArray();
query.First();
query.FirstOrDefault();
etc...

And when using FirstOrDefault, don't forget to check if there is result found by checking if it's not null 当使用FirstOrDefault时,不要忘记检查是否有结果通过检查它是否为空

if(result != null){
    // The result is found :)
}
else {
    // No results :(
}

You can use LINQ to achieve that: 您可以使用LINQ来实现:

var menuItem = menus.Where(m => m.Value == null).OrderBy(m=>m.Order).First();

This assumes that there is at least one item in the list. 这假定列表中至少有一个项目。 If there can be no items you can use .FirstOrDefault() instead. 如果没有项目,您可以使用.FirstOrDefault()代替。

Using LINQ ordering your List by Order then getting the first that has a null value 使用LINQ按顺序排序List,然后获取具有空值的第一个

Menu mn = menus.OrderBy(x => x.Order).FirstOrDefault(m => m.Value == null);
if(mn != null)
{
    // Got it
}
else
{
    // No match for your condition
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM