'Smart' grouping with LINQ

前端 未结 2 823
囚心锁ツ
囚心锁ツ 2020-12-11 18:51

I have a list of strings and I want to convert it to some kind of grouped list, whereby the values would be grouped by their location in the list (not normal grouping, but i

2条回答
  •  一整个雨季
    2020-12-11 19:14

    This is not possible with the Dictionary. A dictionary is associative (i.e.: each key must point to one and one only) and is by nature unordered. You'd need to use something else for that data structure. It wouldn't be terribly hard though!

    Edit

    A List> should do the trick:

    List> structure = new List>();
    structure.Add(new KeyValuePair(myList[0], 1);
    for(int i = 0; i < myList.Count; i++ )
    {
        if( myList[i] == structure[structure.Count-1].Key )
        {
            structure[structure.Count-1].Value += 1;
        }
        else
        {
            structure.Add(new KeyValuePair(myList[i], 1);
        }
    }
    

    After that you should (untested!) have what you're looking for.

    Edit (one more thought)

    While it may be possible with linq (using TakeWhile and counts...), I still think it makes more sense to use a loop here, it's simple. Someone more brilliant than I could try and work with Linq.

提交回复
热议问题