gpt4 book ai didi

c# - 如何比较两个列表并更改一个列表中的一个属性?

转载 作者:行者123 更新时间:2023-12-02 01:27:12 27 4
gpt4 key购买 nike

我有两个列表。我想比较两个列表,并将 Selected bool 属性 falsefirstInstance 更改为 true(如果 selectedInstance 列表项应位于 firstInstance 列表中。我已使用 IEnumerator 尝试了以下代码,但未达到预期效果。

我期待输出:

 List<Data> firstInstance = new List<Data>
{
new Data { AccountNo = 1001,AccountName="AccountName1",BranchName="BranchName1", Selected = false },
new Data { AccountNo = 1101,AccountName="AccountName2",BranchName="BranchName2", Selected = true},
new Data { AccountNo = 1051,AccountName="AccountName3",BranchName="BranchName3", Selected = false },
new Data { AccountNo = 1991,AccountName="AccountName4",BranchName="BranchName4", Selected = true},
new Data { AccountNo = 1234,AccountName="AccountName5",BranchName="BranchName5", Selected = false },
};

我尝试过以下代码:-

static class Program
{
static void Main(string[] args)
{
List<Data> firstInstance = new List<Data>
{
new Data { AccountNo = 1001,AccountName="AccountName1",BranchName="BranchName1", Selected = false },
new Data { AccountNo = 1101,AccountName="AccountName2",BranchName="BranchName2", Selected = false },
new Data { AccountNo = 1051,AccountName="AccountName3",BranchName="BranchName3", Selected = false },
new Data { AccountNo = 1991,AccountName="AccountName4",BranchName="BranchName4", Selected = false },
new Data { AccountNo = 1234,AccountName="AccountName5",BranchName="BranchName5", Selected = false },
};

List<Data> selectedInstance = new List<Data>
{
new Data { AccountNo = 1991,AccountName="AccountName4",BranchName="BranchName4", Selected = true },
new Data { AccountNo = 1101,AccountName="AccountName2",BranchName="BranchName2", Selected = true }
};

firstInstance.CheckActive(selectedInstance);
}

static void CheckActive(this List<Data> firstInstance, List<Data> selectedInstance)
{
using (IEnumerator<Data> firstEnumerator = firstInstance.GetEnumerator(), secondEnumerator = selectedInstance.GetEnumerator())
{
while (true)
{
if (!firstEnumerator.MoveNext() || !secondEnumerator.MoveNext()) break;
if (firstEnumerator.Current.AccountNo == secondEnumerator.Current.AccountNo) firstEnumerator.Current.Selected = true;
}
}
}
}

class Data
{
public int AccountNo { get; set; }
public string AccountName { get; set; }
public string BranchName { get; set; }
public bool Selected { get; set; }
}

最佳答案

您想将第一个列表中与第二个列表(仅包含选定项目)匹配的所有项目的 Selected 属性设置为 true 吗?

那么这个Join方法是高效且有效的:

var query = from activeData in selectedInstance
join allData in firstInstance
on activeData.AccountNo equals allData.AccountNo
select allData;

foreach(Data selectedData in query)
{
selectedData.Selected = true;
}

您的方法不起作用,因为如果一个列表位于末尾,您将停止枚举。但是您必须枚举另一个列表(包含所有数据)直到结束。您还必须将每个项目与所有其他项目进行比较,而不仅仅是在相同的索引处进行比较。

关于c# - 如何比较两个列表并更改一个列表中的一个属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74203774/

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