Need help in a grouping using LINQ in C#

Viewed 160

I have these two classes in my code and a List of Class2. I want to group the list elements by date and ID using LINQ.

public class Class1
{
    public string ID;
    public int y;
    public int z;
}

public class Class2 
{
    public List<Class1> a;
    public int p, q;
    public string s;
    public DateTime date;
}

My list is similar to this:

List<Class2> object1 = new List<Class2>
{
    new Class2 {p = 5, q = 6, date = DateTime.Now, a = new List<Class1> { new Class1 { ID = "3643746HDJ", y = 0, z = 9 }, new Class1 { ID = "746327846HDJ", y = 0, z = 9 } } },
    new Class2 {p = 5, q = 6, date = DateTime.Now.AddDays(1), a = new List<Class1> { new Class1 { ID = "3643746HDJ", y = 0, z = 9 }, new Class1 { ID = "746327846HDJ", y = 0, z = 9 } } },
    new Class2 {p = 5, q = 6, date = DateTime.Now.AddDays(2), a = new List<Class1> { new Class1 { ID = "3643746HDJ", y = 0, z = 9 }, new Class1 { ID = "746327846HDJ", y = 0, z = 9 } } },
    new Class2 {p = 5, q = 6, date = DateTime.Now.AddDays(3), a = new List<Class1> { new Class1 { ID = "3643746HDJ", y = 0, z = 9 }, new Class1 { ID = "746327846HDJ", y = 0, z = 9 } } },
};

Sorry if this is a stupid question, but I am a beginner in C# programming and LINQ and I am not sure if this is even possible.

This is what I have tried based on examples I saw on the web but its not correct

var newList = from item in object1
              group new
              {
                  item.s,
                  item.a[0].x, //I think its wrong because of this
                  item.a[0].y  //and this
              }
              by new
              {
                  item.date,
                  item.a[0].ID  //and this
              }
              into temp
              select temp;

Since I have hardcoded index 0 in the grouping I am missing a lot of elements in my final list. How can I do this for all elements of list a in Class2?

Expected output is similar to this:

Key: {date: 19-09-2017 ID: 3643746HDJ}, Element: {{s: "abc", y = 1, z = 2}, {s: "pqr", y = 2, z = 4}, {s: "abc", y = 1, z = 2}}
Key: {date: 20-09-2017 ID: 3643746HDJ}, Element: {{s: "pop", y = 1, z = 2}, {s: "dfr", y = 2, z = 4}, {s: "abc", y = 1, z = 2}}
Key: {date: 19-09-2017 ID: 746327846HDJ}, Element: {{s: "abc", y = 7, z = 8}, {s: "asar", y = 2, z = 111}, {s: "abc", y = 1, z = 2}}
Key: {date: 20-09-2017 ID: 746327846HDJ}, Element: {{s: "abc", y = 7, z = 8}, {s: "asar", y = 2, z = 111}, {s: "abc", y = 1, z = 2}}
1 Answers
Related