c# - 结合两个不同类型的序列

标签 c# linq collections

我有两个这样定义的类:

class Foo
{
  public string name {get; set;}
  public long number {get; set;}
}

class Bar
{
  //some properties

  public string otherName {get; set;}
  public long otherNumber {get; set;}
}


如何将这两种类型的两个IEnumerable序列组合为一个新的匿名类型,该匿名类型由两个类的属性组成。

例:

Foo:
name1 - number1
name2 - number2
name3 - number3

Bar:
otherName1 - otherNumber1
OtherName2 - otherNumber2

Desired Result:
name1 - number1
name2 - number2
name3 - number3
otherName1 - otherNumber1
OtherName2 - otherNumber2


我在linq中尝试了Zip功能,但没有运气。

最佳答案

用这个:

    var result = efoo.Select(x => new { x = x.name, y = x.number })
                     .Concat(ebar.Select(x => new { x = x.otherName, y = x.otherNumber }));


result是具有xy作为属性的匿名类型的枚举。您可以使用普通的foreach循环遍历此序列:

   foreach (var i in result)
   {
        string name = i.x;
        long number = i.y;
   }

关于c# - 结合两个不同类型的序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33332119/

相关文章:

c# - 如何避免 .NET 中的 InvalidCastException?

c# - 如何退回所有订单的所有订单商品?

arrays - 集合/数组包含方法

c# - 在 ICollection<Tuple<T1,T2>> 上实现 .Contains() 的最简单方法

C#:通过ODBC读取数据算术溢出

c# - 在 NLog 中选择自定义日志级别

c# - Visual Studio C# - 找不到 SQLite.Interop.dll

c# - 如何在 C# 中使用 LINQ 比较两个 List<String>

c# - 如何在 asp.net mvc 中使用 Linq 删除表后重置 id

java - 删除重复项并对字符串数组进行排序