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.date开发者_如何学Go2 = "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
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?
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.
精彩评论