开发者

Null check ObservableCollection before querying it

Is this code good enough:

if (MyCollection.Where(p => p.SomeID == idstring).Any())
{
   selectedval = MyCollection.Where(p => p.SomeID == idstring).FirstOrDefault().MyField;
}

My doubt is about the fact t开发者_StackOverflow社区hat I make the same query twice: first for null check and then to actually get data.

Maybe there is a better way to do this type of things?


Yes.

var item = MyCollection.FirstOrDefault(p => p.SomeID == idstring);
if (item != null)
    selectval = item.MyField;

This avoids double querying the collection, which will certainly make a difference in big collections or if your collection performs a DB query.


There is. You can use the FirstOrDefault method which takes a predicate and returns null if the item is not found.

var result = MyCollection.FirstOrDefault(p => p.SomeID == idstring);
if( result != null )
{
    // item was found
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜