Omar Alaa - 9 months ago 55

C# Question

i am learning C# and LINQ so i am sorry for that question.

how to type in linq to group the same elements in certain array, but when they group it they see if the count of the group is greater than 2 and then division it by 2 and return the value of the group count and then add it to int

what i want the linq to do in code :

`s => s > 2`

s /= 2

return s;

my original code is that:

`int n = Convert.ToInt32(Console.ReadLine());`

string[] userinput = Console.ReadLine().Split(' ');

int[] socks = new int[n];

socks = Array.ConvertAll(userinput, Int32.Parse);

var result = socks.GroupBy(s => s > 2).ToArray(); //This is the line which i want help

int total = 0;

foreach (var group in result)

{

total += group.Count();

Console.WriteLine(group.Count());

}

Lets assume we have 10 kinds of socks. which are 10,20,30,40,50,60,70, 80,90,100

now in the first line i enter the number of the socks i have so for example its 5.

in the second line i enter the 5 socks kinds for example. 10 10 20 20 30

now i want the linq code to define that there is 3 keys here which are 10 20 30, the 10 key has more than only 1 count it has 2. the same for 20 but the 30 only have 1 so lets forget about the 30. now the count of they key of each one of them is 2 so lets divide it by 2 for each one then add the divided number to the total so 2/2 for each one equals 1 so total = 2 (this is the my expected output)

Answer Source

If understand you right, you want to count *pairs* of socks:

```
int total = socks
.GroupBy(x => x)
.Sum(chunk => chunk.Count() / 2);
```

According to your example:

```
[10, 10, 20, 20, 30]
```

after grouping socks by their sizes

```
10: [10, 10] - 2 socks, 1 pair (you've put it as "divide by 2")
20: [20, 20] - 2 socks, 1 pair
30: [30] - 1 sock, 0 pairs
-------------------------------
2 pairs in total (the expected value)
```

My example (from the comments to the question)

```
1, 2, 2, 2, 3, 4, 5, 5
```

should return `2`

as well (we have `2`

pairs: of size `2`

and `5`

)

In case you want to get `pairs`

:

```
var pairs = socks
.GroupBy(x => x)
.Select(chunk => new {
size = chunk.Key,
count = chunk.Count() / 2, });
//.Where(pair => pair.count > 0); // you may want to filter out single socks
```