【问题标题】:Combine two sequences with different types结合两个不同类型的序列
【发布时间】:2015-10-25 16:34:28
【问题描述】:

我有两个这样定义的类:

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 中尝试了Zipfunction,但没有成功。

【问题讨论】:

  • 匿名类型包括“name”、“number”、“othername”和“othernumber”吧?
  • 使用Concat。先有共同的基类或接口,然后将两个列表连接起来。
  • @KundanSinghChouhan 实际上我想将这两个属性合二为一。看看我的例子。
  • @nawfal 我知道Concat 是如何工作的,但问题是关于两个不同的类。

标签: c# linq collections


【解决方案1】:

使用这个:

    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;
   }

【讨论】:

  • 只是好奇,因为我不是 .NET 人:C# 编译器是否合并了这两个匿名类(分别来自两个 Selects)?
  • @LyubomyrShaydariv 是的,它确实将它们连接成一个匿名类型的新序列,具有xy 属性,正如我在回答中指出的那样。然后,您可以使用普通的 foreach 循环遍历此序列。
  • 这很有趣,我从来不知道这样的策略,谢谢。 :) 如果我用不同的方法(在同一个类中)声明这些类怎么办——编译器将如何处理它们?它是否记录在某处?
  • @LyubomyrShaydariv 如果签名匹配,则在一个程序集中将其视为同一类型。匿名类型基于每个程序集。
【解决方案2】:

我不知道连接的意义何在,也不知道以后的用途会如何。您可以将其转换为IEnumerable<object>,然后执行Concat,类似于:

var result = foos.Cast<object>().Concat(bars.Cast<object>());

理想的做法可能是拥有通用的基类或接口,并使用它来代替object

【讨论】:

    【解决方案3】:
    var result = FooList.Select(t=> new { a = t.name, b = t.number})
                        .Concat(
                           BarList.Select(t => new { a = t.othername, b = t.othernumber}));
    

    如果您想“合并”结果,请使用 Union 而不是 Concat - 但在这种情况下,您需要为元素类型提供一个比较函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2011-11-07
      • 2022-12-18
      • 2011-01-16
      • 1970-01-01
      • 2019-06-09
      相关资源
      最近更新 更多