假设我们有两种对象类型:
class Type1
{
public int Value {get;set;}
}
class Type2
{
public int Val {get; set;}
}
我们有两个 IEnumerable:
IEnumerable<Type1> type1col;
IEnumerable<Type2> type2col;
我想要的是:每个 type1col
元素的 Value
属性值都会有足够的 type2col
Val
属性附加值。
我们可以说两个 IEnumerables 的长度总是相同的。
目前我正在使用这个:
for (int i = 0; i < type1col.Count(); i++)
{
type1col.ElementAt(i).Value += type2col.ElementAt(i).Val;
}
但是有没有更好(更快和更短)的方法来做同样的事情?
最佳答案
您可以使用 IEnumerable.Zip
:
var type1Col = type1Col.Select(x => x.Value)
.Zip(type2Col.Select(x => x.Value), (x, y) => x + y)
.Select(x => new Type1 { Value = x });
但是由于您已经有了简单的列表,您还可以使用经典循环并使用索引器代替 IEnumerable.ElementAt
:
for(int i = 0; i < type1Col.Count; i++)
{
type1Col[i].Value += typeo2Col[i];
}
关于c# - 将一个 IEnumerable<Type1> 的值添加到另一个 IEnumerable<Type2>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46483757/