Midhun
Midhun

Reputation: 393

Separate List using LINQ

I have a List of Object with the following properties

public class Class1
{

    public Int64 Id
    {
        get;
        set;
    }

    public Decimal? Amt
    {
        get;
        set;
    }
}

I am creating a list of Object with the above properties

List<Class1> n = new List<Class1>();

Class1 a = new Class1();
Class1 b = new Class1();
Class1 c = new Class1();
Class1 d = new Class1();
Class1 e = new Class1();
Class1 f = new Class1();

a.Id = 1;
a.Amt = 50;
n.Add(a);
b.Id = 2;
b.Amt = 500;
n.Add(b);
c.Id = 1;
c.Amt = 150;
n.Add(c);
d.Id = 2;
d.Amt = 450;
n.Add(d);
e.Id = 1;
e.Amt = 250;
n.Add(e);
f.Id = 2;
f.Amt = 350;
n.Add(f);

I want to group all the objects with same Id in to one list and create another list with this. I have tried to use GroupBy. but in this only first object with the same id is returning.

This is what I tried

List<Class1> m = n.GroupBy(x => x.Id).Select(x => x.FirstOrDefault()).ToList();

Upvotes: 3

Views: 483

Answers (2)

Rubens Farias
Rubens Farias

Reputation: 57956

You grouping is correct, but you must be aware you have more than one duplicated group:

var n = new List<Class1>
{
    new Class1{ Id = 1, Amt =  50 },
    new Class1{ Id = 2, Amt = 500 },
    new Class1{ Id = 1, Amt = 150 },
    new Class1{ Id = 2, Amt = 450 },
    new Class1{ Id = 1, Amt = 250 },
    new Class1{ Id = 2, Amt = 350 },
};

var groups = n.GroupBy(x => x.Id);
foreach (var group in groups.Where(g => g.Count() > 1))
{
     Console.WriteLine("You have {0} items with ID={1}", group.Count(), group.Key);
}

If you just need the duplicated values, you can also do this:

var duplicated = n.GroupBy   (i => i.Id)          // your grouping key
                  .Where     (g => g.Count() > 1) // just duplicated items
                  .SelectMany(g => g)             // flatten those items
                  .ToList    ();

Upvotes: 1

ASh
ASh

Reputation: 35679

if you need all object with the same Id, create a list of lists

List<List<Class1>> m = n.GroupBy(x => x.Id)
                        .Select(x => x.ToList())
                        .ToList();

Upvotes: 4

Related Questions