gpt4 book ai didi

c# - 改进代码 : Compare 2 list of elements

转载 作者:行者123 更新时间:2023-11-30 16:33:16 24 4
gpt4 key购买 nike

抱歉新手问题,但我是编程新手..

我想检查 listOfDifferentTypes 中是否已经只有一个 TypeA 元素。我有以下代码:

     public void CheckType ( Object param)
{
if ( param is TypeA )
{
int i = 0;
TypeA paramToCheck = ( TypeA ) param;

foreach ( var paramB in listOfDifferentTypes )
{
if ( paramB is TypeA )
{
var paramInList = ( TypeA ) paramB;
if ( paramToCheck.ID == paramInList.ID )
{
i++;
}
}
}
if ( i > 1 )
{
paramToCheck.m_Error = "ErrorText";
}
}
}

我认为这不是很干净的解决方案。这段代码可以改进/优化吗?

最佳答案

你可以为此使用 LINQ :) 它看起来不错:

//Checks for string - resplace <string> with <some type> for other types
private bool moreThanOne(List<object> differentTypes)
{
return differentTypes.OfType<string>().Count() > 1;
}

用法:

List<object> listOfDifferentTypes = new List<object> { "string", 13, 52, "string", 54.3f };

var res = moreThanOne(listOfDifferentTypes);

我看到您还检查某种 ID,然后试试这个:

已更新以执行您的代码正在执行的操作

更新:将 .Count() 替换为 .Skip(1).Any(),因此如果找到超过 1 个,它将停止 :)

private void CheckType(object param, List<object> differentTypes)
{
var paramToCheck = param as TypeA;

if (paramToCheck == null) return;

var res = differentTypes.OfType<TypeA>().Where(t => t.ID == paramToCheck.ID).Skip(1).Any();

if (res) paramToCheck.m_Error = "error text";
}

正如我所做的,您可以替换:

if (param is TypeA)
{
TypeA paramToCheck = (TypeA) param;
... Do something

与:

TypeA paramToCheck = param as TypeA; //Returns null if not a TypeA
if (param == null) return;

... Do something

有点快:)

关于c# - 改进代码 : Compare 2 list of elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3404379/

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