Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I trying to group types and its severties on datatable using linq
C#
var query = from row in dt_cv.AsEnumerable()
             group row by new { severity = row.Field<string>("Severity"), 
                          type = row.Field<DateTime>("Type") } into sev
              select new
               {
                Type = sev.Key.type,
                severity = sev.Key.severity,
                sev_count = sev.Count()
               };

When I am trying to get the value of query in foreach loop, it is throwing 'Specified cast is not valid'
C#
foreach (var res in query)
{
  dt.Rows.Add(new object[] { res.Type, res.severity, res.sev_count });
}

Please help.

Thanks in advance
Posted
Comments
Tomas Takac 10-Apr-15 3:07am    
You are casting Type to DateTime and Severity to string. Check if those casts are valid.
srmohanr 10-Apr-15 4:29am    
Thanks Tomas.. I have changed the type from DateTime to String and it works.

As Tomas says, it's the cast in your Linq query that causes the problem. It occurs in the foreach because Linq code is not executed immediately - it is a deferred execution system. When you try to use the query results by including it as a target in the foreach expression, that causes the query to be executed - and so the cast operations happen as part of the foreach.

So as suggested, check your datatypes - the source datatable columns and make sure that casting the "Type" column to a DateTime is valid - I would suspect not, given it's name!
 
Share this answer
 
Comments
Abhinav S 10-Apr-15 3:54am    
5.
Maciej Los 10-Apr-15 4:37am    
+5!
First of all, OriginalGriff is right.
Secondly, i'd suggest to use CopyToDataTable()[^] method instead foreach loop.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900