Separate list using LINQ

I have a list of objects with the following properties

public class Class1
{

    public Int64 Id
    {
        get;
        set;
    }

    public Decimal? Amt
    {
        get;
        set;
    }
}

      

I am creating a list of objects 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 objects with the same ID into one list and create another list with it. I tried using GroupBy. but in this only the first object with the same id is returned.

Here is what I have tried

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

      

+3


source to share


2 answers


if you want the whole object with the same id create a list of lists



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

      

+3


source


You are grouping correctly, but you should be aware that you have more than one duplicate 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 only want duplicate 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    ();

      

+1


source







All Articles