I have a ten element array of integers. I want to sum the elements by group, so for instance I want to add the value at element 0 with the value at element 1, then with the value at element 2, then 3, and so on through to element 9, then add the value at element 1 with the value at 2,3, through to 9 until every group of 2 values has been added together and stored in a variable. I then want to repeat the process with groups of 3, groups of 4, of 5, all the way through to group of 10. Each resultant total being stored in a separate variable. Thus far the only way I can figure out how to do it is thus :-
int i = 0;
int p = 1;
int q = 2;
int r = 3;
while (i < NumArray.Length - 3)
{
while (p < NumArray.Length - 2)
{
while (q < NumArray.Length-1)
{
while (r < NumArray.Length)
{
foursRet += NumArray[i] + NumArray[p] + NumArray[q]+ NumArray[r];
r++;
}
q++;
r = q + 1;
}
p++;
q = p + 1;
r = q + 1;
}
i++;
p = i + 1;
q = i + 2;
r = i + 3;
}
The above is an example of summing groups of 4.
I was wondering if anyone could be kind enough to show me a less verbose and more elegant way of achieving what I want. Many thanks.
Because everything is better with LINQ*:
using System; // Output is below
using System.Linq;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var inputArray = Enumerable.Range(0, 10).ToArray();
var grouped =
from Buckets in Enumerable.Range(1, inputArray.Length)
from IndexInBucket in Enumerable.Range(0, inputArray.Length / Buckets)
let StartPosInOriginalArray = IndexInBucket * Buckets
select new
{
BucketSize = Buckets,
BucketIndex = StartPosInOriginalArray,
Sum = inputArray.Skip(StartPosInOriginalArray).Take(Buckets).Sum()
};
foreach (var group in grouped)
{
Debug.Print(group.ToString());
}
Console.ReadKey();
}
}
} // SCROLL FOR OUTPUT
{ BucketSize = 1, BucketIndex = 0, Sum = 1 }
{ BucketSize = 1, BucketIndex = 1, Sum = 2 }
{ BucketSize = 1, BucketIndex = 2, Sum = 3 }
{ BucketSize = 1, BucketIndex = 3, Sum = 4 }
{ BucketSize = 1, BucketIndex = 4, Sum = 5 }
{ BucketSize = 1, BucketIndex = 5, Sum = 6 }
{ BucketSize = 1, BucketIndex = 6, Sum = 7 }
{ BucketSize = 1, BucketIndex = 7, Sum = 8 }
{ BucketSize = 1, BucketIndex = 8, Sum = 9 }
{ BucketSize = 1, BucketIndex = 9, Sum = 10 }
{ BucketSize = 2, BucketIndex = 0, Sum = 3 }
{ BucketSize = 2, BucketIndex = 2, Sum = 7 }
{ BucketSize = 2, BucketIndex = 4, Sum = 11 }
{ BucketSize = 2, BucketIndex = 6, Sum = 15 }
{ BucketSize = 2, BucketIndex = 8, Sum = 19 }
{ BucketSize = 3, BucketIndex = 0, Sum = 6 }
{ BucketSize = 3, BucketIndex = 3, Sum = 15 }
{ BucketSize = 3, BucketIndex = 6, Sum = 24 }
{ BucketSize = 4, BucketIndex = 0, Sum = 10 }
{ BucketSize = 4, BucketIndex = 4, Sum = 26 }
{ BucketSize = 5, BucketIndex = 0, Sum = 15 }
{ BucketSize = 5, BucketIndex = 5, Sum = 40 }
{ BucketSize = 6, BucketIndex = 0, Sum = 21 }
{ BucketSize = 7, BucketIndex = 0, Sum = 28 }
{ BucketSize = 8, BucketIndex = 0, Sum = 36 }
{ BucketSize = 9, BucketIndex = 0, Sum = 45 }
{ BucketSize = 10, BucketIndex = 0, Sum = 55 }
*Not everything is better with LINQ
If I understand you correctly you have an array of numbers with length n. You want to pick all combinations of m numbers from this. You then want to sum all these combinations and finally compute the sum of these sums.
For instance given n = 6 numbers you can pick m = 4 elements in 15 different ways (the numbers are indices in the array of numbers):
0 1 2 3
0 1 2 4
0 1 3 4
0 2 3 4
1 2 3 4
0 1 2 5
0 1 3 5
0 2 3 5
1 2 3 5
0 1 4 5
0 2 4 5
1 2 4 5
0 3 4 5
1 3 4 5
2 3 4 5
If n < 32 (no more than 31 numbers in your array) you can efficiently generate the indices using 32 bit arithmetic. The following function is based on Gosper's hack:
IEnumerable<UInt32> GetIndexBits(Int32 m, Int32 n) {
unchecked {
var i = (UInt32) (1 << m) - 1;
var max = (UInt32) (1 << n);;
while (i < max) {
yield return i;
var u = (UInt32) (i & -i);
var v = u + i;
i = v + (((v ^ i)/u) >> 2);
}
}
}
With m = 4 and n = 6 this function will generate these numbers (displayed in binary form):
001111
010111
011011
011101
011110
100111
101011
101101
101110
110011
110101
110110
111001
111010
111100
You can then create the sum using LINQ:
var m = 4;
var numbers = new[] { 1, 2, 3, 4, 5, 6 };
var sum = GetIndexBits(4, numbers.Length)
.Select(
bits => Enumerable
.Range(0, numbers.Length)
.Where(i => ((1 << i) & bits) != 0)
)
.Select(indices => indices.Sum(i => numbers[i]))
.Sum();
With the provided input the sum will be 210 which is the same result as foursRet in the question when NumArray contains the numbers 1 to 6.
Related
I'm learning how to program using c#. I'm really new to this.
My question is I'm trying to create an array that shows 10 numbers. I want my code to check which numbers below 10 are divisible for 3 or 5 and sum the total.
I've tried to use the .Sum() function but says int doesn't contain a definition for Sum. I've put using System.Linq on my program.
Does anyone have an idea how to make this sum happens?
{
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int sum = 1 + 2;
foreach (int n in numbers)
{
if (n % 3 == 0 || n % 5 == 0)
{
int total = n.Sum();
Console.WriteLine(total);
}
else
{
Console.WriteLine("not divisible");
}
}`
So your problem is that you are trying to call .Sum() on a variable n which is of type int (you define it here: foreach (int n in numbers), and that is not a method.
Using LINQ you could do something like:
var numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var total = numbers.Where(n => n % 3 == 0 || n % 5 == 0).Sum();
If I understand it correct and using your code this is what you want.
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int sum = 1 + 2;
int total=0;
foreach (int n in numbers)
{
if (n % 3 == 0 || n % 5 == 0)
{
int total += n;
}
else
{
Console.WriteLine("not divisible");
}
}
Console.WriteLine(total);
I moved the printing out to after the foreach so you get one result when it is done
Everybody forgot that array should contain 10 numbers but some numbers values maybe greater than 10. Only number values below 10 should be checked. So a right answer should be
var numbers = new int[] { 1, 9, 5, 6, 8, 10,4, 15, 25, 3};
var total = numbers.Where( n => (n<10) && ( n % 3 == 0 || n % 5 == 0)).Sum();
There is a list of short. The values of it doesn't matter like:
List<short> resultTemp = new List<short>{1,2,3,4,5,6,7,8,9...};
This code should reduse the result list count by removing each Nth item from it.
Example 1:
List<short>{1,2,3,4,5,6,7,8,9,10}.Count == 10;
var targetItemsCount = 5;
result should be {1,3,5,7,9} and result.Count should be == 5
Example 2:
List<short>{1,2,3,4,5,6,7,8,9}.Count == 9;
var targetItemsCo:nt = 3;
result should be {1,4,7} and result.Count should be == 3
But it should stop to remove it, somewhere for make result count equal targetItemsCount (42 in this code, but its value else doesn't matter).
The code is:
var currentItemsCount = resultTemp.Count;
var result = new List<short>();
var targetItemsCount = 42;
var counter = 0;
var counterResettable = 0;
if (targetItemsCount < currentItemsCount)
{
var reduceIndex = (double)currentItemsCount / targetItemsCount;
foreach (var item in resultTemp)
{
if (counterResettable < reduceIndex ||
result.Count + 1 == currentItemsCount - counter)
{
result.Add(item);
counterResettable++;
}
else
{
counterResettable = 0;
}
counter++;
}
}
And the resault.Count in this example equals 41, but should be == targetItemsCount == 42;
Ho do I remove each N item in List untill List.Count more then target value with C#?
If my understanding is correct:
public static void run()
{
var inputs =
new List<Input>{
new Input{
Value = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },`
TargetCount = 5, ExpectedOutput= new List<int>{1,3,5,7,9}
},
new Input{
Value = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
TargetCount = 3, ExpectedOutput= new List<int>{1,4,7}
},
};
foreach (var testInput in inputs)
{
Console.WriteLine($"# Input = [{string.Join(", ", testInput.Value)}]");
var result = Reduce(testInput.Value, testInput.TargetCount);
Console.WriteLine($"# Computed Result = [{string.Join(", ", result)} ]\n");
}
}
static List<int> Reduce(List<int> input, int targetItemsCount)
{
while (input.Count() > targetItemsCount)
{
var nIndex = input.Count() / targetItemsCount;
input = input.Where((x, i) => i % nIndex == 0).ToList();
}
return input;
}
class Input
{
public List<int> ExpectedOutput;
public List<int> Value;
public int TargetCount;
}
Result :
Input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Computed Result = [1, 3, 5, 7, 9 ]
Input = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Computed Result = [1, 4, 7 ]
To guarantee you get the expected number of selected items:
double increment = Convert.ToDouble(resultTemp.Count) / targetItemsCount;
List<short> result = Enumerable.Range(0, targetItemsCount).
Select(x => resultTemp[(int)(x * increment)]).
ToList();
Note that in the following case
List<short>{1,2,3,4,5,6,7,8,9}.Count == 9;
var targetItemsCount = 6;
The result will be [1, 2, 4, 5, 7, 8], i.e. rounding the index down when needed
Also, you'll need to add validation (targetItemsCount > 0, targetItemsCount < resultTemp.Count...)
Link to Fiddle
Give this a try:
var resultTemp = Enumerable.Range(1, 9).ToList();
var targetItemsCount = 3;
var roundingError = resultTemp.Count % targetItemsCount;
var reduceIndex = (resultTemp.Count - roundingError) / targetItemsCount;
List<int> result;
if (reduceIndex <= 1)
result = resultTemp.Take(targetItemsCount).ToList();
else
result = resultTemp.Where((a, index) => index % reduceIndex == 0).Take(targetItemsCount).ToList();
Tried it with your given example, also gave 42 a spin with a list of 1 to 100 it will remove every 2nd item till it reaches 42, so the last entry in the list would be 83.
As I said, give it a try and let me know if it fits your requirement.
I am trying to keep all the combinations (5C1, 5C2, 5C3, 5C4, 5C5) of 1,2,3,4,5 into individual array. So I need to create dynamic array using for loop in c#.
Say for example,
Here n = 5 and r = 1 to 5.
if r = 1 then
My array will be single dimensional array, when r = 2 then it will be two dimensional array, when r = 3 then three dimensional, when r = 4 then four dimensional array and it will e continued up to end of 5.
My code is given below
string[] ShipArrayObj;
public frmResult( string[] ShipArray )
{
InitializeComponent();
ShipArrayObj = ShipArray;
}
private void frmResult_Load(object sender, EventArgs e)
{
string[] arr = ShipArrayObj;
int n = ShipArrayObj.Count();
for (int r = 1; r <= n; r++)
{
StoreCombination(arr, n, r);
richTextBox1.Text = richTextBox1.Text + "/";
}
}
void StoreCombination(string[] arr, int n, int r)
{
string[] data = new string[r];
createCombination (arr, data, 0, n - 1, 0, r);
}
private void createCombination(string[] arr, string[] data, int start, int end, int index, int r)
{
if (index == r)
{
int j = 0;
for (j = 0; j < r; j++)
richTextBox1.Text = richTextBox1.Text + data[j].ToString();//Where I want to set array to keep combination values
return;
}
int i = 0;
for (i = start; i <= end && end - i + 1 >= r - index; i++)
{
data[index] = arr[i];
CreateCombination(arr, data, i + 1, end, index + 1, r);
}
}
I am storing all the combination into a Rich Text Box, but want to keep into array. If anybody help me then I will be grateful to you.
If you're used to something like Java then multidimensional arrays are a little different in syntax in C#.
Here's a page describing how to do them in C#. Here's a snippet from said page:
// Two-dimensional array.
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// The same array with dimensions specified.
int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// A similar array with string elements.
string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" },
{ "five", "six" } };
// Three-dimensional array.
int[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } } };
// The same array with dimensions specified.
int[, ,] array3Da = new int[2, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } } };
If you're interested in different combinations of things with a fixed number of them, something like this should be all you need.
If you're interested in different combinations of things with a dynamic number of them, something like this should be all you need.
(Unless you're trying to optimize performance, it's better to be readable/expressive, generally speaking.)
You may need to consider whether or not order matters (un-ordered set vs. ordered list). I would assume it doesn't from your code (in which case sorting is good to eliminate "duplicates"), but I can't tell for sure.
Here's a good example that's easy to read and modify for variations and isn't so bad for small numbers:
// -1, 0, ..., 5
var choices = Enumerable.Range(-1, 6);
var possibleChoices =
from a in choices
from b in choices
from c in choices
from d in choices
from e in choices
select (IEnumerable<int>)new [] { a, b, c, d, e };
// Remove -1's because they represent not being in the choice.
possibleChoices =
possibleChoices.Select(c => c.Where(d => d >= 0));
// Remove choices that have non-unique digits.
possibleChoices =
possibleChoices.Where(c => c.Distinct().Count() == c.Count());
// Sort the choices to indicate order doesn't matter
possibleChoices =
possibleChoices.Select(c => c.OrderBy(d => d));
// Remove duplicates
possibleChoices =
possibleChoices.Select(c => new
{
Key = string.Join(",", c),
Choice = c
}).
GroupBy(c => c.Key).
Select(g => g.FirstOrDefault().Choice);
foreach (var choice in possibleChoices) {
Console.Out.WriteLine(string.Join(", ", choice));
}
Output:
0
1
2
3
4
0, 1
0, 2
0, 3
0, 4
1, 2
1, 3
1, 4
2, 3
2, 4
3, 4
0, 1, 2
0, 1, 3
0, 1, 4
0, 2, 3
0, 2, 4
0, 3, 4
1, 2, 3
1, 2, 4
1, 3, 4
2, 3, 4
0, 1, 2, 3
0, 1, 2, 4
0, 1, 3, 4
0, 2, 3, 4
1, 2, 3, 4
0, 1, 2, 3, 4
This is probably a little more dense to understand, hard-coded to this specific variation of combination and involves recursion but is a bit more generic/isn't hard-coded to 5 (and took 0.047s on dotnetfiddle.net instead of 0.094s). It's also completely lazy/IEnumerable.
public static void Main()
{
var possibleChoices = Choose(5);
foreach (var choice in possibleChoices) {
Console.Out.WriteLine(string.Join(", ", choice));
}
}
public static IEnumerable<IEnumerable<int>> Choose(int max)
{
var remaining = Enumerable.Range(0, max);
return ChooseRecursive(remaining, Enumerable.Empty<int>());
}
public static IEnumerable<IEnumerable<int>> ChooseRecursive(IEnumerable<int> remaining, IEnumerable<int> chosen)
{
yield return chosen;
foreach (var digit in remaining)
{
var choices = ChooseRecursive(
remaining.Where(d => d > digit),
chosen.Concat(new [] { digit })
);
foreach (var choice in choices)
{
yield return choice;
}
}
}
Output:
0
0, 1
0, 1, 2
0, 1, 2, 3
0, 1, 2, 3, 4
0, 1, 2, 4
0, 1, 3
0, 1, 3, 4
0, 1, 4
0, 2
0, 2, 3
0, 2, 3, 4
0, 2, 4
0, 3
0, 3, 4
0, 4
1
1, 2
1, 2, 3
1, 2, 3, 4
1, 2, 4
1, 3
1, 3, 4
1, 4
2
2, 3
2, 3, 4
2, 4
3
3, 4
4
Having a list of structs OR maybe an array List each with 3 elements, like
12 8 7
5 1 0
7 3 2
10 6 5
6 2 1
8 4 3
6 1 5
7 2 6
8 3 7
9 4 8
11 7 6
13 9 8
11 6 10
12 7 11
13 8 12
14 9 13
I want to get rid of items that have 2 common subitems in list, in the example I would like to remove
5 1 0
6 2 1
6 1 5
7 3 2
7 2 6
8 4 3
8 3 7 has 2 same items as row 7,3,2
9 4 8 has 2 same items as row 8,4,3
10 6 5
11 7 6
11 6 10 has 2 same items as row 11,7,6
12 7 11 has 2 same items as row 11,7,10
12 8 7
13 8 12
13 9 8
14 9 13 has 2 same items as row 13,9,8
So using structs approach I am thinking in sorting the list by element A, then looping and comparing elements, in a way that If current element has 2 values equal to other element in list I do not add it to a result List, however I got stuck and do not know if there is a better approach
struct S
{
public int A;
public int B;
public int C;
}
public void test()
{
List<S> DataItems = new List<S>();
DataItems.Add(new S { A = 1, B = 2, C=3} );
DataItems.Add(new S { A = 12, B = 8, C = 7 });
DataItems.Add(new S { A = 5, B = 1, C = 0 });
DataItems.Add(new S { A = 7, B = 3, C = 2 });
DataItems.Add(new S { A = 10, B = 6, C = 5 });
DataItems.Add(new S { A = 6, B = 2, C = 1 });
DataItems.Add(new S { A = 8, B = 4, C = 3 });
DataItems.Add(new S { A = 6, B = 1, C = 5 });
DataItems.Add(new S { A = 7, B = 2, C = 6 });
DataItems.Add(new S { A = 8, B = 3, C = 7 });
DataItems.Add(new S { A = 9, B = 4, C = 8 });
DataItems.Add(new S { A = 11, B = 7, C = 6 });
DataItems.Add(new S { A = 13, B = 9, C = 8 });
DataItems.Add(new S { A = 11, B = 6, C = 10 });
DataItems.Add(new S { A = 12, B = 7, C = 11 });
DataItems.Add(new S { A = 13, B = 8, C = 12 });
DataItems.Add(new S { A = 14, B = 9, C = 13 });
var sortedList = DataItems.OrderBy(x => x.A);
List<S> resultList = new List<S>();
for (int i = 0; i < sortedList.Count (); i++)
{
for (int j = i+1; j < sortedList.Count(); j++)
{
if (sortedList.ElementAt(i).A == sortedList.ElementAt(j).A || sortedList.ElementAt(i).A == sortedList.ElementAt(j).B || sortedList.ElementAt(i).A == sortedList.ElementAt(j).C)
{
//ONE HIT, WAIT OTHER
}
}
}
}
Is there a more efficient way to get the list without having item with 2 same items so I would get, instead of hardcoding the solution?
5 1 0
6 2 1
6 1 5
7 3 2
7 2 6
8 4 3
10 6 5
11 7 6
12 8 7
13 8 12
13 9 8
Given an item...
{ A = 1, B = 2, C = 3 }
You have 3 possible combinations that could be repeated in another item, e.g.
AB, AC & BC which is {1, 2}, {1, 3} & {2, 3}
So what I would do is iterate through your list, add those combinations to a dictionary with a separator char (lowest number first so if B < A then add BA rather than AB). So you dictionary keys might be...
"1-2", "1-3", "2-3"
Now as you add each item, check if the key already exists, if it does then you can ignore that item (don't add it to the results list).
Performance-wise this would be once through the whole list and using the dictionary to check for items with 2 common numbers.
One way to solve it is by introducing intermediate methods in the struct S:
public struct S {
public int A;
public int B;
public int C;
public bool IsSimilarTo(S s) {
int similarity = HasElement(A, s) ? 1 : 0;
similarity += HasElement(B, s) ? 1 : 0;
return similarity >= 2 ? true : HasElement(C, s);
}
public bool HasElement(int val, S s) {
return val == s.A || val == s.B || val == s.C;
}
public int HasSimilarInList(List<S> list, int index) {
if (index == 0)
return -1;
for (int i = 0; i < index; ++i)//compare with the previous items
if (IsSimilarTo(list[i]))
return i;
return -1;
}
}
Then you can solve it like this without ordering:
public void test() {
List<S> DataItems = new List<S>();
DataItems.Add(new S { A = 1, B = 2, C = 3 });
DataItems.Add(new S { A = 12, B = 8, C = 7 });
DataItems.Add(new S { A = 5, B = 1, C = 0 });
DataItems.Add(new S { A = 7, B = 3, C = 2 });
DataItems.Add(new S { A = 10, B = 6, C = 5 });
DataItems.Add(new S { A = 6, B = 2, C = 1 });
DataItems.Add(new S { A = 8, B = 4, C = 3 });
DataItems.Add(new S { A = 6, B = 1, C = 5 });
DataItems.Add(new S { A = 7, B = 2, C = 6 });
DataItems.Add(new S { A = 8, B = 3, C = 7 });
DataItems.Add(new S { A = 9, B = 4, C = 8 });
DataItems.Add(new S { A = 11, B = 7, C = 6 });
DataItems.Add(new S { A = 13, B = 9, C = 8 });
DataItems.Add(new S { A = 11, B = 6, C = 10 });
DataItems.Add(new S { A = 12, B = 7, C = 11 });
DataItems.Add(new S { A = 13, B = 8, C = 12 });
DataItems.Add(new S { A = 14, B = 9, C = 13 });
int index = 1; //0-th element does not need to be checked
while (index < DataItems.Count) {
int isSimilarTo = DataItems[index].HasSimilarInList(DataItems, index);
if (isSimilarTo == -1) {
++index;
continue;
}
DataItems.RemoveAt(index);
}
}
I'd like to know the best way to approach this. I have an integer array (say of 3, 4, 8, 10, 15, 24, 29, 30) and I want to sort it into 3 groups: 4 times table, 5 times table, and neither).
As the groups would suggest, it would sort the array into the 4 and 5 times table with another for items that aren't present in either.
What's the best way to approach this in C#? I'm currently using this:
int[] iArray = new int[]{3, 4, 8, 10, 15, 24, 29, 30};
var iE = iArray.GroupBy ((e) => {
if (e % 4 == 0) {
return "four";
} else if (e % 5 == 0) {
return "five";
} else {
return "other";
}
}).OrderBy (e => e.Count ());
Produces:
4
4
8
24
5
10
15
30
Other
3
29
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
If you want to get all multiples of 4 and all multiples of 5 (and have some overlap between the two) you can do this:
List<int> multiplesOf4 = (from i in arr where i % 4 == 0 select i).ToList();
List<int> multiplesOf5 = (from i in arr where i % 5 == 0 select i).ToList();
List<int> others = (from i in arr where i % 5 != 0 && i % 4 != 0 select i).ToList();
If you want no overlap, however, you need to pick which one will be dominant. I chose 4 here:
List<int> multiplesOf4 = new List<int>(),
multiplesOf5 = new List<int>(),
others = new List<int>();
foreach (int i in arr)
{
if (i % 4 == 0)
multiplesOf4.Add(i);
else if (i % 5 == 0)
multiplesOf5.Add(i);
else
others.Add(i);
}
Try this:
var numberGroupsTimes5 =
from n in numbers
group n by n % 5 into g
where g.Key == 0
select new { Remainder = g.Key, Numbers = g };
var numberGroupsTimes4 =
from n in numbers
group n by n % 4 into g
where g.Key == 0
select new { Remainder = g.Key, Numbers = g };
foreach (var g in numberGroupsTimes5)
{
string st = string.Format("Numbers with a remainder of {0} when divided by 5:" , g.Remainder);
MessageBox.Show("" + st);
foreach (var n in g.Numbers)
{
MessageBox.Show(""+n);
}
}
foreach (var g in numberGroupsTimes4)
{
string st = string.Format("Numbers with a remainder of {0} when divided by 4:", g.Remainder);
MessageBox.Show("" + st);
foreach (var n in g.Numbers)
{
MessageBox.Show("" + n);
}
}
You approach is correct. But you can do some small improvements to make it more readable and standard:
var iArray = new[] { 3, 4, 8, 10, 15, 24, 29, 30 };//Don't need to give type(int) explicitly
var iE = iArray.GroupBy(e => e % 4 == 0 ? "four" : e % 5 == 0 ? "five" : "other").OrderBy(e => e.Count());
It'll give the same results.