Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map two lists using linq

If i have a List of dates like this :

List<DateTime>  {5-10-2014,6-10-2014,7-10-2014}

and i have list of sessions like this :

List<int>  {1,2,3,4,5,6}

How to map the sessions to dates considering that each date has two sessions in order(using linq).


i want the result like that :

5-10-2014    1
5-10-2014    2
6-10-2014    3
6-10-2014    4
7-10-2014    5
7-10-2014    6
like image 245
Anyname Donotcare Avatar asked Dec 11 '22 03:12

Anyname Donotcare


1 Answers

Here's one way you could do it with GroupJoin:

var groupedDates = dates
    .Select((date, index) => new { Date = date, Index = index })
    .GroupJoin(
        numbers,
        dateWithIndex => dateWithIndex.Index,
        num => (num - 1) / 2,
        (dateWithIndex, nums) => new[] 
        { 
            new { Date = dateWithIndex.Date, Number = nums.First() },
            new { Date = dateWithIndex.Date, Number = nums.Last() }
        })
    .SelectMany(grp => grp);

Example: https://dotnetfiddle.net/2IIKhj

Here's how this works:

  1. Project the dates list into a new sequence containing the index of each date and the date itself
  2. GroupJoin that collection with the list of numbers. To correlate the two, use the Index we got from step 1 for the date, and (num - 1) / 2, since Index is zero-based.
  3. To build the reusult, create a new array containing two items, one for each number associated with the date.
  4. Finally, call SelectMany to flatten the sequence.
like image 114
Andrew Whitaker Avatar answered Dec 26 '22 22:12

Andrew Whitaker