简体   繁体   中英

Output of a linq query --> System.Linq.Lookup`2+Grouping[System.Int32,System.Int32]

I want the number of an array with odd occurrences.

This is my code. I think it is working but I cannot output the expected number 2 as a string. I got

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

instead.

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());

Try this:

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

Your approach to solving the problem is wrong, the grouped values are instances of Grouping so you have to select the appropriate values by the key.

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);

So, in this example, you should have two as the return value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM