Click here to Skip to main content
15,888,461 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I am trying to Group elements on the remainder of an integer when they are divided by 5.

C#
nt[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

Such that, for instance, numbers with a remainder of 0 when divided by 5 are -- > 5 and 0 (0, new [] {5, 0})

However, I am receiving the following error:

I understand that it expects the Enumerable return type instead of IGrouping, but I cannot figure out how to fix it. Any help would be appreciated. Thank you.

Error	CS0266	Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<<anonymous type: int Key, System.Linq.IGrouping<int, int> g>>'  
           
  to
 'System.Collections.Generic.IEnumerable<(int remainder, System.Collections.Generic.IEnumerable<int> numbers)>'


What I have tried:

C#
public static IEnumerable<(int remainder, IEnumerable<int> numbers)> Grouping()
        {
            int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

            var numberGroups = from n in numbers
                               group n by n % 5 into g
                               select new { g.Key, g };

            return numberGroups;
        }
Posted
Updated 4-Mar-22 10:32am
v2

1 solution

Try this:

C#
void Main()
{
	int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
	
	var result = Grouping(numbers);
	result.Dump();
}

// Define other methods and classes here
public static IEnumerable<(int remainder, IEnumerable<int> numbers)> Grouping(int[] input)
{
    return input
		.GroupBy(n => n % 5)
        .Select(grp=> (grp.Key, grp.Select(x=> x)));
}
 
Share this answer
 
Comments
LuckyChloe 3-Mar-22 17:39pm    
💖
Maciej Los 4-Mar-22 1:52am    
:D
Richard Deeming 4-Mar-22 3:49am    
Or with the query syntax:
var numberGroups = from n in numbers
                   group n by n % 5 into g
                   select (g.Key, g.AsEnumerable());
Maciej Los 4-Mar-22 5:04am    
Oh, yeah! I do like a lambda expression version ;)
LuckyChloe 4-Mar-22 7:27am    
It was very useful thank you. I now know what AsEnumerable() is used for.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900