user8189013
user8189013

Reputation:

Multiple column group by on Linq

I want to use group by on multiple columns however, couldn't understand how should i select the SAMPLE_TIME and even if i write Manuel date to sample time I get following error;

System.InvalidCastException: 'System.ValueTuple`2[System.String,System.String]' 'System.String'

Currently What i use is like below;

var dt = (from dr1 in dtTopAll.AsEnumerable()
                          where  dr1.Field<DateTime>("SAMPLE_TIME") <= maxDate
                          group dr1 by ("WAIT_CLASS", "SAMPLE_TIME")  into g
                          select new
                          {
                              SAMPLE_TIME = // How can i select sample_time,
                              WAIT_CLASS = g.Key,
                              WAITS = g.Sum(z => z.Field<double>("WAITS") / 100)
                          }).ToDataTable();

Upvotes: 2

Views: 122

Answers (2)

user4482825
user4482825

Reputation:

What you need to is create a new anonymous type on group by using group by new and if you want to select you can use your alias. Please check this; Group By Multiple Column In LINQ in C#

Upvotes: 0

sujith karivelil
sujith karivelil

Reputation: 29006

Have you tried this:

var dt = (from dr1 in dtTopAll.AsEnumerable()
          where  dr1.Field<DateTime>("SAMPLE_TIME") <= maxDate
          group dr1 by new 
                       {
                          WAIT_CLASS = dr1.Field<string>("WAIT_CLASS"),
                          SAMPLE_TIME = dr1.Field<DateTime>("SAMPLE_TIME")
                       } into g
          select new
                    {
                        SAMPLE_TIME = g.Key.SAMPLE_TIME,
                        WAIT_CLASS = g.Key.WAIT_CLASS,
                        WAITS = g.Sum(z => z.Field<double>("WAITS") / 100)
                    }).ToDataTable();

Upvotes: 1

Related Questions