I have a list of string tuples, say (P1,P2)
I'd like to know if there's a LINQ statement where I could group by P1 (in ascending order), and have that group contain all the P2 values for the group (in descending order).
For input: ("A","B"), ("A","C"), ("D","B") I'd like to get two groups: "A" and "D" (in that order, every time) where group "A" contains "C" and "B" (in that order, every time) and group "D" contains, well, "B".
Is this possible with the built-in LINQ classes or do I need to iterate the groups and sort them myself?
Nope, it's not hard - you just need to keep track of whether you're looking at a group or elements within the group. Here's a sample query:
Here's a complete example (avoiding .NET 4's
Tuple
type just for simplicity if you're using .NET 3.5):Note that it can be slightly simpler if you're happy to do the ordering on a "need to know" basis: