6

也许是深夜,但我被难住了。我正在尝试将具有相同属性的多个列表合并为一个。我认为 LINQ 的 .UNION 可以解决问题,但我错了。这是我的一些列表的示例:

LIST1 (report names):
Date      Name    Title         Product
02/01/13  Steve   Hello World   Report
02/05/13  Greg    Howdy         Report

LIST2 (song names):
Date      Name    Title         Product
01/01/13  John    Time          Song
01/05/13  Bob     Sorry         Song

LIST3 (games names):
Date      Name      Title         Product
12/01/12  Google    Bike Race     Game
12/05/12  Apple     Temple Run    Game

我的课很简单。这是它的样子:

public class MyClass {
  public DateTime Date { get; set; }
  public string Name { get; set; }
  public string Title { get; set; }
  public string Product { get; set; }
}

如果您想知道,我使用此 LINQ 查询来获取上述列表之一:

var finalList = Games
  .Select (s => new MyClass { 
    Date = (System.DateTime) s.Games.Creation_date,
    Name = s.Games.Last_name,
    Title = string.Format("{0} (Report)", s.Game.Headline),
    Product="Report"
  })
  ;

到目前为止,这很容易,但我想将所有列表合并为 1。所以,我的最终列表应该如下所示:

Date      Name    Title         Product
02/01/13  Steve   Hello World   Report
02/05/13  Greg    Howdy         Report
01/01/13  John    Time          Song
01/05/13  Bob     Sorry         Song
12/01/12  Google  Bike Race     Game
12/05/12  Apple   Temple Run    Game

我认为 UNION 命令可以做到这一点:

var newList = List1.Union(List2).Union(List3);

但我没有得到想要的输出。

Date      Name    Title         Product
02/01/13  Steve   Hello World   Report
02/05/13  Greg    Howdy         Report
01/01/13  Bob     Time          Game
01/05/13  John    Sorry         Song
12/01/12  Google  Bike Race     Song
12/05/12  Apple   Temple Run    Game

知道我在这里做错了什么吗?

4

2 回答 2

16

尝试:

list1.Concat(list2).Concat(list3);

无论如何,您都不想使用Union(工作与否),因为它确实设置了联合。

于 2013-02-07T04:28:17.553 回答
1

您可以尝试使用 AddRange 命令应该看起来像这样

var FullList = list1.AddRange(list2).AddRange(list3);

或者故障安全方式应该是

var FullList = list1.Concat(list2).Concat(list3).ToList(); //Personally i would use this

或者你也有

var FullList = new[] { list1, list2, list3 }.SelectMany(a => GetAllProducts(a)).ToList();
于 2013-02-07T04:50:02.993 回答