I am trying to see if I can use LINQ to solve a problem I am having. I have a collection of items that contain an Enum (TypeCode) and a User object, and I need to flatten it out to show in a grid. It's hard to explain, so let me show a quick example.
Collection has items like so:
TypeCode | User
---------------
1 | Don Smith
1 | Mike Jones
1 | James Ray
2 | Tom Rizzo
2 | Alex Homes
3 | Andy Bates
I need the output to be:
1 | 2 | 3
Don Smith | Tom Rizzo | Andy Bates
Mike Jones | Alex Homes |
James Ray | |
Thanks to anyone who can help me! I've tried doing this using foreach, but I can't do it that way because I'd be inserting new items to the collection in the foreach, causing an error.
I guess this is similar to Marc's answer, but I'll post it since I spent some time working on it. The results are separated by
" | "
as in your example. It also uses theIGrouping<int, string>
type returned from the LINQ query when using a group by instead of constructing a new anonymous type. This is tested, working code.I also tested it with this input:
Which produced the following results showing that the first column doesn't need to contain the longest list. You could use
OrderBy
to get the columns ordered by TypeCode if needed.@Sanjaya.Tio I was intrigued by your answer and created this adaptation which minimizes keySelector execution. (untested)
Marc's answer gives sparse matrix that can't be pumped into Grid directly.
I tried to expand the code from the link provided by Vasu as below:
* can't say anything about the performance though.
You can use Linq's .ToLookup to group in the manner you are looking for.
Then it's a matter of putting it into a form that your consumer can make sense of. For instance:
Put that in an IEnumerable<> method and it will (probably) return a collection (rows) of collections (column) of User where a null is put in a column that has no data.
I'm not saying it is a great way to pivot - but it is a pivot...