通过将对象列表与另一个列表进行比较,从对象列表中删除条目
Remove entries from a List of objects by comparing it with another List
我需要删除 List<Dto>
中的所有条目,比如 master[]
,其中存在另一个列表,即 Dto.ListOfIds
,比如 a[]
,它是 List<int>
。我有另一个列表,List<int>
,比如 b[]
,我需要将其与 a[]
进行比较,并从 master[]
中删除所有条目,其中 a[]
和 b[]
没有共同元素。
添加一些代码片段..希望这有帮助
var projectIds = invoiceListRequestDto.ProjectIds.Split(",").Select(int.Parse).Distinct().ToList();
invoiceList.ForEach(invoice=>
{
var invoiceProjectIds = invoice.ProjectReferenceNo.Split(",").Select(int.Parse).Distinct().ToList();
if(invoiceProjectIds.Any(x=> projectIds.Any(t=> x==t)))
{
//logic here
}
});
invoiceList 是 master[]
,projectIds 是 a[]
,invoiceProjectIds 是 [b]
。
实际上,a[]
和 b[]
是由逗号分隔的字符串组成的[仅供参考]
正在添加一些示例数据..
让master[]=[{other stuff , b="3,4,5,6" } ,a[]=[1,2]
和 b[]=[3,4,5,6]
.
这里,由于a[]
和b[]
没有共同元素,master[]
运算后应该为null。
谁能帮我解决一下这个逻辑。
提前致谢。
为了简化事情,您可以添加一个辅助方法来解析 ID:
IEnumerable<int> ParseInts(string csv)
{
return csv.Split(",").Select(int.Parse).Distinct();
}
您不应该在迭代时修改列表。
一种方法是创建一个新列表:
var projectIds = ParseInts(invoiceListRequestDto.ProjectIds).ToArray();
invoiceList = invoiceList
.Where(x => ParseInts(x.ProjectReferenceNo).Intersect(projectIds).Any())
.ToList();
或者您可以使用 List<T>.RemoveAll
就地修改列表:
invoiceList.RemoveAll(x => !ParseInts(x.ProjectReferenceNo).Intersect(projectIds).Any());
我需要删除 List<Dto>
中的所有条目,比如 master[]
,其中存在另一个列表,即 Dto.ListOfIds
,比如 a[]
,它是 List<int>
。我有另一个列表,List<int>
,比如 b[]
,我需要将其与 a[]
进行比较,并从 master[]
中删除所有条目,其中 a[]
和 b[]
没有共同元素。
添加一些代码片段..希望这有帮助
var projectIds = invoiceListRequestDto.ProjectIds.Split(",").Select(int.Parse).Distinct().ToList();
invoiceList.ForEach(invoice=>
{
var invoiceProjectIds = invoice.ProjectReferenceNo.Split(",").Select(int.Parse).Distinct().ToList();
if(invoiceProjectIds.Any(x=> projectIds.Any(t=> x==t)))
{
//logic here
}
});
invoiceList 是 master[]
,projectIds 是 a[]
,invoiceProjectIds 是 [b]
。
实际上,a[]
和 b[]
是由逗号分隔的字符串组成的[仅供参考]
正在添加一些示例数据..
让master[]=[{other stuff , b="3,4,5,6" } ,a[]=[1,2]
和 b[]=[3,4,5,6]
.
这里,由于a[]
和b[]
没有共同元素,master[]
运算后应该为null。
谁能帮我解决一下这个逻辑。
提前致谢。
为了简化事情,您可以添加一个辅助方法来解析 ID:
IEnumerable<int> ParseInts(string csv)
{
return csv.Split(",").Select(int.Parse).Distinct();
}
您不应该在迭代时修改列表。
一种方法是创建一个新列表:
var projectIds = ParseInts(invoiceListRequestDto.ProjectIds).ToArray();
invoiceList = invoiceList
.Where(x => ParseInts(x.ProjectReferenceNo).Intersect(projectIds).Any())
.ToList();
或者您可以使用 List<T>.RemoveAll
就地修改列表:
invoiceList.RemoveAll(x => !ParseInts(x.ProjectReferenceNo).Intersect(projectIds).Any());