gpt4 book ai didi

c# - 遍历 2 个列表

转载 作者:太空狗 更新时间:2023-10-29 22:07:40 25 4
gpt4 key购买 nike

我有一个 List<T1>项目和第二个List<T2>项目。这两个列表都按属性 A 的字母顺序排序。我知道 List<T2> 中的项目列表是 List<T1> 的子集List<T2> 中没有项目List<T1> 中不存在的存在.

我需要遍历 List<T1>并在每次与 List<T2> 中的变量匹配时更改一个变量.最快最好的方法是什么?我假设我需要遍历两个列表,但我知道做一个嵌套的 foreach 是没有意义的。

最佳答案

对于这种类型的事情,我更喜欢双遍历 for 循环。请参见下面的示例。

var super = new List<Contact>();
super.Add(new Contact() {Name = "John"});
super.Add(new Contact() {Name = "Larry"});
super.Add(new Contact() {Name = "Smith"});
super.Add(new Contact() {Name = "Corey"});

var sub = new List<Contact>();
sub.Add(new Contact() {Name = "Larry"});
sub.Add(new Contact() {Name = "Smith"});

var subCount = 0;
for(int i=0; i<super.Count && subCount < sub.Count; i++)
{
if (super[i].Name == sub[subCount].Name)
{
Act(super[i], sub[subCount]);
subCount++;
}
}

Act(...) 执行您想要执行的任何操作。

循环每次都会递增 super 列表,但只会在找到匹配项时递增子列表。

请注意,这仅适用于您的两个假设。 1) 列表都已排序,并且 2) 第二个列表是第一个列表的子集。

关于c# - 遍历 2 个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3292503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com