Frage

So I have a dataview that pulls back some information related to an agency and I would like to group the data by agency, so that name only appears once, then order alphabetically, then by Level. Level would refer to Level 1, Level 2, Level 3. Is it possible to do this in Linq? If so, how? Thanks.

EnumerableRowCollection<DataRow> query = 
     from agency in dtAllContacts.AsEnumerable()
     orderby agency.Field<Int32?>("ID") == null ? 0 : agency.Field<Int32>("ID")
     orderby agency.Field<Int32>("Level")  
     select agency;
War es hilfreich?

Lösung

Your current code is not working, because you sort collection two times - first time by id, and than you sort it again, but by level. What you need is sorting by id AND level at same time. So, you need single orderby operator:

 from agency in dtAllContacts.AsEnumerable()
 orderby agency.Field<Int32?>("ID") == null ? 0 : agency.Field<Int32>("ID"),
         agency.Field<Int32>("Level")  
 select agency;

That will generate ThenBy operator. Also you can simplify first condition by using GetValueOrDefault method of nullable type:

 orderby agency.Field<int?>("ID").GetValueOrDefault(),
         agency.Field<int>("Level")
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top