Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# select elements from IList

Tags:

c#

linq

I have a list of objects, IList<O>. O has several properties but only two of them are relevant: Date and Duration.

I want to "split" the list into several lists that contain only the objects that have matching Date and Duration Properties.

Example:

0- Date==1, Duration==7  
1- Date==1, Duration==7  
2- Date==2, Duration==7  
3- Date==2, Duration==7  
4- Date==2, Duration==14  
5- Date==2, Duration==14  

Desired result (IList<IList<O>>):

0-  
 0- Date==1, Duration==7  
 1- Date==1, Duration==7  
1-  
 0- Date==2, Duration==7  
 1- Date==2, Duration==7  
2-  
 0- Date==2, Duration==14  
 1- Date==2, Duration==14  

I know this can be done with some LINQ selects but am not sure how.

like image 566
drupop Avatar asked Mar 15 '26 08:03

drupop


1 Answers

You can use the following:

var query = 
    from item in list
    group item by new { item.Date, item.Duration } into g
    select g.toList();
var result = query.toList();

This creates an anonymous class with the properties that you want to group by. It then expands the IGrouping to a List of the original type. The query is then run to produce the outer List.

like image 78
Ben Lings Avatar answered Mar 16 '26 21:03

Ben Lings



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!