1

I want a select the first group in the list. Is there a better way to do this.

Here is how I'm doing it:

var match = (from m in recordList select m).FirstOrDefault();

var matches = recordList.Where(d => d.DateDetails == match.DateDetails);
var lookup = matches.ToLookup(a => a.DateDetails).First();

lookaheadList = lookup.ToList();

I'm selecting the first group and pushing it into a second list called lookaheadlist.

My DATA is as follows:

DateDetails      Track Details 
0025              ABCD 
0025             EFGH 
0030               XXXXX 
0030               XXXXX
Christos
  • 53,228
  • 8
  • 76
  • 108
user726720
  • 1,127
  • 7
  • 25
  • 59

3 Answers3

1

There is no need for the ToLookup. The lookup groups by different DateDetails, but matches is already filtered to a single date, so there is already only one group to select.

You could skip the filter and just go with:

var match = recordList.ToLookup(a => a.DateDetails).First()

lookaheadList = match.ToList();

However, this is redundant for a couple of reasons:

  • If you're not storing the result of ToLookup and using it to look up other groups by date, there was no point creating the lookup object -- you could have just used GroupBy.

  • If you only need the first group, there is no need for any grouping at all (either by ToLookup or GroupBy).

To directly grab the items that match the first date, use:

var firstDate = recordList.First().DateDetails;

var matches = recordList.Where(d => d.DateDetails == firstDate)

lookaheadList = matches.ToList();
nmclean
  • 7,564
  • 2
  • 28
  • 37
0

Assuming

group1 = "025"

and

group2= "030"

I think you're missing a "group by"

C# LINQ Query - Group By

Community
  • 1
  • 1
0

I suggest you to use GroupBy

var match = (from m in recordList select m).FirstOrDefault();

var firstGroup= recordList.Where(d => d.DateDetails == match.DateDetails).GroupBy(x=> x.DateDetails).Select(x => x.First());

and then use firstGroup variable to filter that elements

have a read at this @Jon Skeet answer about the comparison of ILookup and IGrouping performances

Bear in mind that ToLookup is a "do it now" operation (immediate execution) whereas a GroupBy is deferred

Community
  • 1
  • 1
faby
  • 7,394
  • 3
  • 27
  • 44