Filtering 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 time) datetime objects from two object properties.

Example

I have 2 objects with two 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"

They are saved in the list:

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

I need to run LINQ for objList to create 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
+3
source share
2 answers

It looks like you want something like:

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

Does it look right at you?

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

You can use Concatand suggested by Jon or SelectMany(which seems more natural to me).

, MyObject DateTime , .

+2

Source: https://habr.com/ru/post/1735554/


All Articles