Sahil
Sahil

Reputation: 137

Group a list of objects and assign values to groups

class user    
{
    public string userID { get; set; }
    public string groupID { get; set; }
    public int individualCredit { get; set; }
    public int groupCredit { get; set; }
}

I have a list like this

 List<user> listUsers = new List<user>();

I need to do following things and I'm giving what I have tried so far.

I want to group users with same groupID.

Calculate groupCredit by adding the individualcredit s of each member in group and by dividing it by the number of group members.

Finally I want to assign each user with their groupCredit. There are groups with three to five members.

Can anyone help me in this? at least give me a sample solved question? I searched but I didn't find anything quite matching with this.

This is my linq so far

var groups = lstUsers.GroupBy(x => x.groupID).Select(g => new {ID=g.Key,count=g.Count() });

Here the thing I don't understand to do is get the group mark (It's calculated adding all group members marks and dividing it by number of group members) and to assign group mark to each member in a group.

Upvotes: 0

Views: 1928

Answers (3)

Edin
Edin

Reputation: 1496

var groups = listUsers.GroupBy(x => x.groupID)
                .Select(g => new { ID = g.Key, AverageCredit = g.Average(u => u.individualCredit) });

foreach (var user in listUsers)
    user.groupCredit = groups.First(u => u.ID == user.groupID).AverageCredit;

Upvotes: 1

CharlesNRice
CharlesNRice

Reputation: 3259

Since classes are by reference you can just add that to the anonymous type. then you don't have to relookup by the key

var listUsers = new List<user>();
var groups = listUsers.GroupBy(x => x.groupID).Select(g => new { users = g, groupCredit = g.Average(u => u.individualCredit) });
foreach (var group in groups)
{
    foreach (var member in group.users)
    {
        // Avg is a decimal have to cast back to int for class
        member.groupCredit = (int)group.groupCredit;
    }
}

Upvotes: 0

Andrei
Andrei

Reputation: 56698

You do all querying in one LINQ expression, and then set everything in a loop.

var credits = lstUsers.GroupBy(x => x.groupID)
        .Select(g => {ID = g.Key, Credit = g.Sum(x => x.individualCredit)/g.Count()});

foreach (var user in lstUsers)
{
    user.groupCredit = credits.Single(x => x.ID == user.groupID).Credit;
}

Upvotes: 0

Related Questions