[英]Linq query where clause in sub list
Trying to get instances with only certain sub instances.试图获取只有某些子实例的实例。
Having two classes:有两个类:
class Center
{
public int Id { get; set; }
public string Name { get; set; }
public List<Sub> SubList { get; set; }
}
class Sub
{
public string Code { get; set; }
public DateTime? EndDate { get; set; }
}
Filled with data:填充数据:
void Main()
{
var list = new List<Center>();
list.Add(new Center
{
Id = 1,
Name = "Main1",
SubList = new List<Sub>
{
new Sub { Code = "A", EndDate = null },
new Sub { Code = "B", EndDate = new DateTime(2021,2,1) },
new Sub { Code = "C", EndDate = new DateTime(2021,2,1) },
}
});
list.Add(new Center
{
Id = 2,
Name = "Main2",
SubList = new List<Sub>
{
new Sub { Code = "X", EndDate = null },
new Sub { Code = "Y", EndDate = null },
new Sub { Code = "Z", EndDate = null },
}
});
}
I want to get a list of 'Centers' with only the SubList where enddate is null or in the future.我想获得一个“中心”列表,其中只有结束日期为 null 或将来的子列表。 So the result should be (in json):
所以结果应该是(在json中):
[
{
"Id": 1,
"Name": "Main1",
"SubList": [
{
"Code": "A",
"EndDate": null
}
]
},
{
"Id": 2,
"Name": "Main2",
"SubList": [
{
"Code": "X",
"EndDate": null
},
{
"Code": "Y",
"EndDate": null
},
{
"Code": "Z",
"EndDate": "2021-06-04T00:00:00"
}
]
}
]
Came up with:想出了:
var l = list.Select(
x =>
new
{
x.Id,
x.Name,
SubList = x.SubList.Where(s => s.EndDate == null || s.EndDate > DateTime.Now)
});
This is the result I want, but can this be done more easily?这是我想要的结果,但这可以更容易地完成吗? Something like:
就像是:
var l = list.Where(x => x.SubList.Where(s => s.EndDate == null || s.EndDate > DateTime.Now)
I would recommend to add a copy method in your Center
and Sub
class:我建议在您的
Center
和Sub
class 中添加一个复制方法:
class Center
{
public int Id { get; set; }
public string Name { get; set; }
public List<Sub> SubList { get; set; }
public Center Copy()
{
return new Center { Id = this.Id, Name = this.Name, SubList = this.SubList.Select(x => x.Copy()).ToList() };
}
}
class Sub
{
public string Code { get; set; }
public DateTime? EndDate { get; set; }
public Sub Copy()
{
return new Sub { Code = this.Code, EndDate = this.EndDate };
}
}
Then you can first copy your List:然后你可以先复制你的列表:
var l = list.Select(center => center.Copy()).ToList();
It's not LINQ, but you can modify this copy with ForEach
of List<T>
:它不是 LINQ,但您可以使用
List<T>
的ForEach
修改此副本:
l.ForEach(x => x.SubList = x.SubList.Where(s => s.EndDate == null || s.EndDate > DateTime.Now).ToList());
If it's ok to modify the original list, you don't need the copy stuff.如果可以修改原始列表,则不需要复制的东西。 Just use:
只需使用:
list.ForEach(x => x.SubList = x.SubList.Where(s => s.EndDate == null || s.EndDate > DateTime.Now).ToList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.