c# - 将一个 IEnumerable<Type1> 的值添加到另一个 IEnumerable<Type2>

标签 c# linq

假设我们有两种对象类型:

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/

相关文章:

c# - 当结构未初始化时编译器给出错误,如果我们尝试访问属性而不是变量

c# - 在提供程序连接上启动事务时发生错误。有关详细信息,请参阅内部异常

c# - 如何在 lambda 表达式中定义为 LINQ Select 方法中的另一个函数

c# - 更新 Sharepoint 列表项

c# - 错误 APPX3212 : SDK root folder for 'Portable 7.0' cannot be located

c# - 当前上下文中不存在名称 'DefaultAuthenticationTypes'

c# - 如何处理意外的日期和时间格式?

c# - 如何查询 Entity Framework 中的非映射属性?

c# - 比较两个节点列表的总匹配度

c# - 如何在linq where子句中比较int和string