user576914
user576914

Reputation: 199

Create a new List from existing one and group objects

I have a List<> with User objects (username(string) and grade(string))

List<User> users = new List<User>();

The List gets populated with values from DB(or Text File) and I have a List with 5 objects:

user1 A
user1 B
user2 A
user2 G
user3 D

I want to modify the List(or create a new List) so the result should be a new List with htis values:

user1 A,B
user2 A,G
user3 D

I tried GroupBy :

var result = jquery.GroupBy(u => u.username).OrderByDescending(g => g.Count()).Select(g => g.Key);

But I want to have the result in a new List

Upvotes: 0

Views: 167

Answers (3)

Rahul Singh
Rahul Singh

Reputation: 21795

Try this:-

var query = users.GroupBy(x => x.UserName).OrderByDescending(x => x.Count())
                                        .Select(x => new { UserName = x.Key, Grades = String.Join(",", x.Select(z => z.Grade)) });

Working Fiddle.

Upvotes: 1

Max Brodin
Max Brodin

Reputation: 3938

Try this

var result = users
            .GroupBy(x => x.Name)
            .OrderByDescending(g => g.Count())
            .Select(g => new { Name = g.Key, Grades = string.Join(",", g.Select(x => x.Grade) });

Here is code sample

Upvotes: 2

Christos
Christos

Reputation: 53958

You could built a new type, that will hold the information you want, like

public class UserGrade
{
    // the user's name.
    public string UserName { get; set;}

    // a comma separated list of the grades achieved by the user.
    public string Grades { get; set; }
}

Then we groub by our results by the username and we select for each group a bew UserGrade object. Last we call ToList, in order we get our result as a list:

var result = jquery.GroupBy(u => u.username)
                   .Select(x=> new UserGrade{
                       UserName = x.Key,
                       Grades = String.Join(",",x.Select(y=>y.Grade)
                 }).ToList();

Note You could avoid the definition of the new type. In this case your list, will hold a sequence of obejcts of an anonymous type.

Upvotes: 1

Related Questions