抱歉新手问题,但我是编程的新手..
我想检查TypeA
中listOfDifferentTypes
中是否只有一个元素 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";
}
}
}
。我跟着代码:
{{1}}
我认为这不是一个非常干净的解决方案。这段代码可以改进/优化吗?
答案 0 :(得分:2)
你可以使用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,然后试试这个:
更新以执行您的代码正在执行的操作
更新:用.Skip(1).Any()替换.Count(),如果找到超过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
速度快一点:)
答案 1 :(得分:1)
原始解决方案,重写:
public void CheckType(Object param)
{
TypeA paramToCheck = param as TypeA;
int count = 0;
if (paramToCheck != null)
{
foreach (var paramB in listOfDifferentTypes)
{
var paramInList = paramB as TypeA;
if (paramInList != null && paramToCheck.ID == paramInList.ID)
{
count++;
if (count > 1)
{
paramToCheck.m_Error = "ErrorText";
break;
}
}
}
}
}
注意:
as
关键字与null
进行比较,以执行类型转换,if
语句(使用AND(&&
)运算符),break
语句退出foreach
循环。编辑:更新re:评论(感谢您指出我之前的错误!)