-3

I have list of projects. In every project I calculate some values for every user that are part of project. So on exit i get something like this -

Project1
user1 - value1
user2 - value2

Project2
user1 - value3
user3 - value4

...

Project10
user8 - value5
user9 - value6

I want to transform it in next form :

User1
Project1 - value1
Project2 - value3

User2
Project1 - value2

...

User9
Project10 - value6

I need some idea or example how to implement it.

For me it seems like i need create some collection where key can be un-unique (key - it can be User name and values - value for user). So i can go through list of projects, add keyValue pair to output list. Or there is better approach?

demo
  • 6,038
  • 19
  • 75
  • 149
  • use group-by on users... http://stackoverflow.com/questions/7325278/group-by-in-linq – A.T. Sep 22 '15 at 08:30
  • @A.T. i can use groub-by on users in case i have such simple logic, where i can easily get access to users. But it isn't my case. In loop through project list I call API method to get that users... So for me this isn't answer – demo Sep 22 '15 at 08:37
  • it's not an answer it's a comment, anyway you should draft such complexity in questions so we can better answer. – A.T. Sep 22 '15 at 08:39

1 Answers1

0

You can use a Lookup<Tkey,TValue> which allows duplicate keys since the value is always an IEnumerable<TValue>, so even an non-available key returns Enumerable<TValue>.Empty().

var userLookup = projectList.ToLookup(p => p.User);

Now you can lookup a specific user in this way:

IEnumerable<Project> userProjects = userLookup["User1"]; // presuming it's a string

Another option is to use GroupBy:

var userGroups = projectList
    .GroupBy(p => p.User)
    .OrderBy(g => g.Key);


foreach(var grp in userGroups)
{
    Console.WriteLine(grp.Key); // user
    foreach(Project p in grp)
        Console.WriteLine("{0} - {1}", p.Name, p.Value);
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939