【问题标题】:Output of a linq query --> System.Linq.Lookup`2+Grouping[System.Int32,System.Int32]linq 查询的输出 --> System.Linq.Lookup`2+Grouping[System.Int32,System.Int32]
【发布时间】:2017-10-22 06:35:29
【问题描述】:

我想要奇数出现的数组的数量。

这是我的代码。我认为它正在工作,但我无法将预期的数字 2 输出为字符串。我得到了

System.Linq.Lookup`2+Grouping[System.Int32,System.Int32]

改为。

int[] array = { 0, 0, 1, 1, 2 };
var result = array.GroupBy(a => a)
                  .Select(o => o)
                  .Where(o => (o.Count() % 2 == 1))
                  .FirstOrDefault();
Console.WriteLine(result.ToString());

【问题讨论】:

    标签: c# linq format output


    【解决方案1】:

    试试这个:

    var result = array.GroupBy(a => a)
        .Where(o => o.Count() % 2 == 1)
        .FirstOrDefault().Key;
    

    【讨论】:

    • 您可以通过传递FirstOrDefault 的谓词来做得更好:array.GroupBy(a => a) .FirstOrDefault(o => o.Count() % 2 == 1).Key
    【解决方案2】:

    您解决问题的方法是错误的,分组值是Grouping 的实例,因此您必须按键选择适当的值。

    int[] array = { 0, 0, 1, 1, 2 };
    var result = array.GroupBy(a => a)
                      .Where(o => (o.Count() % 2 == 1))
                      .Select(o => o.Key);
    string resultString = string.Join(", ", result.ToArray());
    Console.WriteLine(resultString);
    

    所以,在这个例子中,你应该有两个作为返回值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 2018-02-17
      • 2014-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多