【问题标题】:Using Contains() on Collection of Anonymous Types在匿名类型集合上使用 Contains()
【发布时间】:2011-09-19 02:27:17
【问题描述】:

我仍在学习 LINQ,并且我有一个匿名类型的集合,使用类似以下的方法获得。 [mycontext] 是我的实际数据源的占位符:

var items = from item in [mycontext]
            select new { item.col1, item.col2, item.col3 };

如何使用items.Contains() 来确定@​​987654323@ 是否包含匹配值?

我正在搜索的值是不是匿名类型。所以我需要编写自己的比较逻辑,最好是 lambda 表达式。

【问题讨论】:

  • 在您学习的同时,获取一份 LinqPad 的副本。这是一个非常有用的工具,有很多很好的例子。
  • @Mr Moose:上周知道了。谢谢。

标签: c# linq contains


【解决方案1】:

如果您更喜欢使用谓词,那么您最好使用Any 而不是Contains

bool exists = items.Any(x => x.col1 == "foo"
                             && x.col2 == "bar"
                             && x.col3 == 42);

【讨论】:

    【解决方案2】:

    试试 LINQ Any() 方法:

    if (items.Any(i => i.col1 == myOtherThing.Value))
    {
        // Effectively Contains() == true
    }
    

    【讨论】:

    • 这个版本解决了我的情况,逻辑是匹配col1,而不是整个item
    【解决方案3】:

    或者您可以使用带有谓词的“Any”方法。

    bool exists = items.Any( i => {logic} );
    

    【讨论】:

      猜你喜欢
      • 2010-10-14
      • 1970-01-01
      • 1970-01-01
      • 2011-09-05
      • 2012-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-08
      相关资源
      最近更新 更多