Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter a list of objects using LINQ

I have a list of custom objects. These objects have 2 datetime properties on them. I need to get a list of unique (ignore the time part) datetime objects from the two objects properties.

Example

I have 2 objects with 2 datetime properties:

object1.date1 = "01/01/2001 12:54"
object2.date1 = "01/02/2001 12:51"
object3.date1 = "01/01/2001 23:45"
object4.date1 = "01/02/2001 12:54"
object5.date1 = "01/01/2001 18:22"

object1.date2 = "09/01/2001 15:54"
object2.date2 = "09/02/2001 18:51"
object3.date2 = "08/01/2001 21:45"
object4.date2 = "08/02/2001 02:54"
object5.date2 = "07/01/2001 05:22"

These are stored in a list:

List<MyObject>() objList = new List<MyObject>()
objList.add(object1);
objList.add(object2);

I need to perform some LINQ on objList to produce a new List containing the following datetime objects in it:

01/01/2001 00:00
01/02/2001 00:00
09/01/2001 00:00
09/02/2001 00:00
08/01/2001 00:00
08/02/2001 00:00
07/01/2001 00:00
like image 655
CeejeeB Avatar asked Jan 26 '26 21:01

CeejeeB


2 Answers

It sounds like you want something like:

var newList = objList.Select(x => x.date1.Date)
                     .Concat(objList.Select(x => x.date2.Date))
                     .Distinct()
                     .ToList();

Does that look about right to you?

like image 117
Jon Skeet Avatar answered Jan 29 '26 10:01

Jon Skeet


var dates = objects
    .SelectMany(o => new[] { o.date1, o.date2 })
    .Select(d => DateTime.Parse(d).Date)
    .Distinct();

You can either use Concat and Jon suggested or SelectMany (which looks more natural to me).

Of course, ideally would be to encapsulate date parsing logic into MyObject class and expose DateTime properties rather than plain strings.

like image 43
Konstantin Spirin Avatar answered Jan 29 '26 09:01

Konstantin Spirin



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!