Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pairing two arrays

Tags:

c#

linq

Suppose I have two arrays of always equal length that could look like this:

{"A", "C", "A", "A", "B", "B", "A", "A" }
{ 1, 1, 2, 3, 1, 10, 5, 7 }

Data is paired by array index.

I wish to use LINQ to produce a result that looks like below:

A: { 1, 2, 3, 5, 7 }
B: { 1, 10 }
C: { 1 }

How can I accomplish that?

The arrays come from http request parameters. The letters applies to database names and the integers are ids in a table in the database. Next step is to connect to each database and get some data for each id.

like image 320
Mr. Blonde Avatar asked Jun 01 '26 17:06

Mr. Blonde


1 Answers

You can first Zip them, and then group them. Use the grouped result to construct a dictionary, or whatever type you want.

string[] first = { "A", "C", "A", "A", "B", "B", "A", "A" };
int[] second = { 1, 1, 2, 3, 1, 10, 5, 7 };

var list = first.Zip(second, (f, s) => new { First = f, Second = s });

Dictionary<string, int[]> d = list.GroupBy(i => i.First)
                                  .ToDictionary(k => k.Key, v => v.Select(val => val.Second)
                                                                  .ToArray()
                                               );
like image 135
Patrick Hofman Avatar answered Jun 03 '26 06:06

Patrick Hofman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!