Jerry
Jerry

Reputation: 77

How to select records with duplicate column by group using LINQ?

For some reason some records have the same ID. Aim is to list all the whole record which have the same ID. For example, how can group the following records by GroupId using LINQ, and find all records with the same ID and list them all? (thus merging all rows in each group into one)

var list = new List<Record>()
{ 
    new Record() { GroupId = 0, ValueA = 20, ValueB = 300 },
    new Record() { GroupId = 1, ValueA = 30, ValueB = 700 },
    new Record() { GroupId = 1, ValueA = 40, ValueB = 500 },
    new Record() { GroupId = 2, ValueA = 80, ValueB = 300 },
    new Record() { GroupId = 2, ValueA = 20, ValueB = 200 },
    new Record() { GroupId = 2, ValueA = 20, ValueB = 200 }
};

Expect result is the last 5 records.

Upvotes: 1

Views: 3786

Answers (3)

Sandy
Sandy

Reputation: 11697

Another way is:

var results = (from l in list
        group new {l.ValueA, l.ValueB} by l.GroupId
        into g
        select new {GroupId = g.Key, Values = g.ToList()}).ToList();

If you prefer lambda expression, then

var results = (list.GroupBy(l => l.GroupId, l => new {l.ValueA, l.ValueB})
        .Select(g => new {GroupId = g.Key, Values = g.ToList()})).ToList();

This should give you records based on unique GroupIdalong the other values associated.

EDIT

foreach (var result in results)
{
    foreach (var value in result.Values)
    {
        int valueA = value.ValueA;
        int valueB = value.ValueB;
    }
}

I think you are looking for something similar to this.

Hope it helps.

Upvotes: 3

Backs
Backs

Reputation: 24913

var groups = list.ToLookup(record => record.GroupId);
var groups1 = groups[1]; //all records with GroupId = 1

Upvotes: 1

Sameer
Sameer

Reputation: 2171

Answer for "how can group the following records by GroupId using LINQ"

var groupList = list.GroupBy((mRecord) => mRecord.GroupId).ToList();

Upvotes: 2

Related Questions