[英]Using Contains() on Collection of Anonymous Types
我還在學習LINQ,我有一些使用以下內容獲得的匿名類型的集合。 [mycontext]是我實際數據源的占位符:
var items = from item in [mycontext]
select new { item.col1, item.col2, item.col3 };
如何使用items.Contains()
來確定items
包含匹配值?
我要搜索的值不是匿名類型。 所以我需要編寫自己的比較邏輯,最好是作為lambda表達式。
如果你更喜歡使用謂詞,那么你可能最好使用Any
而不是Contains
:
bool exists = items.Any(x => x.col1 == "foo"
&& x.col2 == "bar"
&& x.col3 == 42);
嘗試LINQ Any()
方法:
if (items.Any(i => i.col1 == myOtherThing.Value))
{
// Effectively Contains() == true
}
或者您可以將“Any”方法與謂詞一起使用。
bool exists = items.Any( i => {logic} );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.