0

I have ORM data type like below

public class PackData
{
   public int PackId
   public int ClientId
   public DateTime DateCreated
   public List<PackItemData> PackItems
}

public class PackItemData
{
   public int PackId
   public string DeviceId
}

I can query PackData and PackItemData with Linq

var data = DataTable.Where(pack =>  pack.DateCreated >= startDate 
                                    && pack.DateCreated <= endDate)

I want to group/distinct child data (PackItemData) to get unique result for device Id

How can I achieve that?

Kjartan
  • 18,591
  • 15
  • 71
  • 96
navirius
  • 209
  • 1
  • 7
  • 14

4 Answers4

0

I think you are looking for SelectMany. This will flatten out your List<List<PackItemData>> to List<PackItemData>

var data=DataTable.Where(pack =>  pack.DateCreated >= startDate 
                                  && pack.DateCreated <= endDate)
                   .SelectMany(i => i.PackItems)
                   .GroupBy(i => i.DeviceId).Select(i => i.First());
Aducci
  • 26,101
  • 8
  • 63
  • 67
  • But what will be the output of this query?? He wanted to group items ryt?? This query will provide only the distinct deviceids.. – Arun Aravind Apr 01 '14 at 12:43
  • This query give me a PackItems result data, how can I get PackData list result that pack items already distinct by device Id for all pack datas? – navirius Apr 02 '14 at 03:13
0
var groups = DataTable
    .Where(pack => pack.DateCreated >= startDate && pack.DateCreated <= endDate)
    .SelectMany(pack => pack.PackItems)
    .GroupBy(item => item.DeviceId);

You might want to start with SelectMany which will allow you to enumerate over all of the PackItems in all of the PackDatas. This gives you an IEnumerable<PackItemData> which you can then use in your grouping.

0

Linq GroupBy and Distinct methods should get you what you need.

var data=DataTable.Where(pack => pack.DateCreated >= startDate && pack.DateCreated <= endDate)
                  .Select( pack => pack.PackItems)
                  .GroupBy( p => p.PackId, p => p.DeviceId, (key, p) => new PackItemData { PackId = key, DeviceId = p});

I'm not 100% this works, as I have yet to run a test, but this should get you close to where you're going.

Source: Group by in LINQ

Community
  • 1
  • 1
CodeMonkey1313
  • 15,717
  • 17
  • 76
  • 109
0
 var data = DataTable.Where(pack =>  pack.DateCreated >= startDate 
                              && pack.DateCreated <= endDate).SelectMany(s=> s.PackItems).GroupBy(p => p.DeviceId).Select(r=> r);

I think this should work.

Humayoun Kabir
  • 275
  • 1
  • 9
  • This query give me a PackItems result data, how can I get PackData list result that pack items already distinct by device Id for all pack datas – navirius Apr 02 '14 at 03:13