【问题标题】:How do I query list for any matches on item property? [duplicate]如何查询列表以查找项目属性上的任何匹配项? [复制]
【发布时间】:2016-03-31 14:02:14
【问题描述】:

我有一个List<Tuple<int, string>>。我想得到一个 bool 指示是否有任何 int 值匹配。比如:

{1, "Yada"}, {2, "Data"} 返回false
{1, "Yada"}, {1, "Data"} 返回true

可以吗?

【问题讨论】:

  • 是的,但这个问题涉及List<int>,我有一个List<Tuple<int, string>>
  • 这是相同的前提 - 按您的键值分组,看看有多少组有多个元素。
  • 好吧,这就是它的工作原理

标签: c# linq properties


【解决方案1】:

是的,可以通过分组来完成:

bool match = list.GroupBy(tuple => tuple.Item1, t => t).Any(group => group.Count() > 1);

【讨论】:

  • 我在c#深渊中的救星!
【解决方案2】:

只需按该值分组,看看是否有任何组有多个项目:

bool hasDupes =
    list.GroupBy(t => t.Item1)
        .Any(g => g.Count() > 1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 2018-03-13
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    相关资源
    最近更新 更多