Grouping a List - Finding a Better Way

I have a list of something like

var x = new List<string>{"A","B","C","D","E","F"};

I want to group it in two-locale types

1-A

1-B

2-C

2-D

3rd

3-f

Whats my decision

        var result = new Dictionary<int, List<string>>();

        var sequence = 1;

        var groupList = new List<string>();

        for (var i = 0; i < x.Length ; i++)
        {
            groupList.Add(x[i]);

            if ((i + 1)%2 == 0)
            {
                result.Add(sequence, groupList);
                groupList = new List<string>();
                sequence++;
            }

        }

        return result;

I am looking for alternative (best) ways to get the same result.

+3
source share
3 answers

This will do the same.

var y = x.GroupBy(i =>Convert.ToInt32((x.IndexOf(i) + 1.1) * 0.5));
+1
source

Here is another way:

    int numPairs = 3;
    char[] abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();         
    var dict = new Dictionary<int, char[]>();
    for (int i = 1, k=1; i <= numPairs && k<abc.Length; i++, k+=2)
    {
        dict.Add(i, new char[] { abc[k - 1], abc[k] });
    }
    return dict;
+1
source

I think this is a readable Linq solution:

var result = x
      .Select((value, index) => new { value, index })
      .GroupBy(arg => arg.index / 2 + 1, arg => arg.value);  

Selectimplements a value with an index into an anonymous type, and GroupBy- by index.

If you need groupings in Dictionary, as in your question, use ToDictionary:

var dictionary = result.ToDictionary(
      grouping => grouping.Key, 
      grouping => grouping.ToList());
+1
source

All Articles