I’ve hunted around for this, and I am sure that I am just missing it because I not that good with Linq.
I have a list that looks like:
type=a, value=aaaa
type=a, value=bbbb
type=b, value=cccc
type=d, value=dddd
type=d, value=eeee
type=d, value=ffff
type=a, value=gggg
type=b, value=hhhh
type=b, value=iiii
type=b, value=jjjj
I would like to break this into sub lists, without sorting (I need the original order maintained). I would like to get back these lists, in this order in a list of lists or something similar:
List 1
type=a, value=aaaa
type=a, value=bbbb
List2
type=b, value=cccc
List 3
type=d, value=dddd
type=d, value=eeee
type=d, value=ffff
List 4
type=a, value=gggg
List 5
type=b, value=hhhh
type=b, value=iiii
type=b, value=jjjj
I would imagine that looping is not the best answer.
Any ideas much appreciated.
Long live stackoverflow.com!
Chris
Edit After Four Answers:
I checked the answers from:
* Enigmativity
* Bert Evans
* Risky Martin
* david.s
They all work nicely. Bert Evans brought up performance, which isn’t a big concern for me in this case, but I did some quick checking for the sake of the post.
I didn’t modify anyone’s code, just timed it doing 4,000 of these operations on rather short lists.
Risky’s answer was the fastest.
Bert’s answer was only a tad slower.
david’s and Enigmativity were hardly any slower, really.
I marked Risky’s answer as accepted because of performance and for pointing to the related post early on, and then coming back to provide an answer.
I would agree that Bert’s is the most readable, though.
I honestly don’t know which one I will use… actually, I will use Enigmativity’s solution because it has already taken into account that i only need the values and one key per subgroup.
This could be generalized or made into an extension method, but you get the idea:
Using this class:
Edit: Here are the tradeoffs for this solution:
Pros:
Cons:
itemstwice. This isn’t a big deal ifitemsis a List, but ifitemsis an IEnumerable that performs an expensive computation for each item, this method could be slower than other methods.If you want
itemsto be iterated once with lazy evaluation, I recommend the GroupAdjacent extension method as mentioned in this answer or looping withyield return. If you want one iteration without lazy evaluation, I recommend looping or theAggregatemethod.