Domanda

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;
È stato utile?

Soluzione

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")
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top