简体   繁体   English

从列表中的两个不同对象返回LINQ select查询中的特定对象

[英]Return a specific object in a LINQ select query from two different objects in a list

I have a list that could contain eg. 我有一个可能包含例如的列表。 the following objects 以下对象

ObjectFirst {
id = 1;
mode = Constants.Active;
}

ObjectSecond {
id = 2;
mode = Constants.Passive;
}

How can I make a LINQ query that selects the object with "mode = Constants.Active" if that exists and if not it selects the object with the "mode = Constants.Passive"? 如果存在,我如何进行LINQ查询来选择带有“ mode = Constants.Active”的对象,如果不存在,它将如何选择带有“ mode = Constants.Passive”的对象? Only one object should be returned. 仅应返回一个对象。 I would like to solve this with one LINQ query. 我想用一个LINQ查询解决这个问题。

I am not sure if that could be done in one query but it could be done in multiple ways, You can try: 我不确定是否可以在一个查询中完成,但是可以通过多种方式完成,您可以尝试:

var obj = list.Any(r=> r.mode == Constants.Active) ? 
                            list.FirstOrDefault(r=> r.mode == Constants.Active)
                            list.FirstOrDefault(r=> r.mode == Constants.Passive);

Or: 要么:

var obj = list.FirstOrDefault(r=> r.mode == Constants.Active);
if(obj == null)
{
   obj = list.FirstOrDefault(r=> r.mode == Constants.Passive);
}

In theory you could order them by the mode , thus giving them a priority, and then return the first. 从理论上讲,您可以通过mode对它们进行排序,从而给它们一个优先级,然后再返回第一个。 Assuming that Constants.Active is lower than Constants.Passive . 假设Constants.Active低于Constants.Passive

var obj = list.OrderBy(r => r.mode).FirstOrDefault()

Optionally, you could add some extra checking: (可选)您可以添加一些额外的检查:

var obj = list.Where(r => r.Id == someId).OrderBy(r => r.mode).FirstOrDefault()

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

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