[英]Can I get a property from a collection using Linq in a more elegant way than this?
I have a collection of items 我有一些物品
List<Thing> MyListOfThings
I get this list from a db using PetaPoco like this 我像这样使用PetaPoco从数据库中获得此列表
var MyListOfThings = db.Fetch<Thing>();
Then I want to get the value of a property like this: 然后,我想获得像这样的属性的值:
otherObject.Value = MyListOfThings.SingleOrDefault(q => q.UniqueID == otherValue).SomeProperty;
I think this is a very elegant solution, the problem is if the collection does not contain an object with the UniqueID
of otherValue
. 我认为这是一个非常优雅的解决方案,问题是如果集合中不包含具有
otherValue
的UniqueID
的otherValue
。 Then it goes BANG with a null reference exception. 然后它以无效引用异常进入BANG。
The solution I have been using is 我一直在使用的解决方案是
otherObject.Value = MyListOfThings.SingleOrDefault(q => q.UniqueID == otherValue) == null
? ""
: MyListOfThings.SingleOrDefault(q => q.UniqueID == otherValue).SomeProperty;
This works, Resharper still complains that there is a possible NullReferenceException, but I guess that's just because it doesn't count the first line as a nullcheck. 这有效,Resharper仍然抱怨可能存在NullReferenceException,但是我想那仅仅是因为它没有将第一行计为nullcheck。
However... this looks ugly and is so unDRY that it's dripping... 但是...看起来很丑而且很干燥以至于滴下...
Is there a more elegant solution for this? 有没有更优雅的解决方案呢?
It looks like SomeProperty
is a string
, and you want string.Empty
as a fallback value. 看起来
SomeProperty
是string
,并且您想要string.Empty
作为后备值。 If that's right, then you can do 如果是这样,那么您可以
otherObject.Value =
(from thing in MyListOfThings
where thing.UniqueID == otherValue
select thing.SomeProperty)
.SingleOrDefault() ?? string.Empty;
The LINQ expression is an IEnumerable<string>
containing the SomeProperty
value of all Thing
s having the relevant UniqueID
; LINQ表达式是
IEnumerable<string>
包含具有相关UniqueID
的所有Thing
的SomeProperty
值; this might be an empty enumerable. 这可能是一个空的枚举。
Use a where statement first and use DefaultIfEmpty to set your fallback value 首先使用where语句,然后使用DefaultIfEmpty设置后备值
otherObject.Value = MyListOfThings
.Where(q => q.UniqueID == otherValue)
.Select(q => q.SomeProperty)
.DefaultIfEmpty("")
.SingleOrDefault();
Do it like this 像这样做
MyListOfThings object = MyListOfThings.where(q => q.UniqueID == otherValue).FirstOrDefault();
This will either get an object of my thing or null 这将得到我的东西的对象或为null
if(!object.IsNull) // null check so wont Bang
{
//assign value here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.