[英]Concat/Union Tables in LINQ
這個當前項目更像是一個更大項目的概念證明。 我有兩個“表”(表示為下面的列表), CatList
和DogList
,它們具有相同的列結構。 我希望能夠Concat
或Union
這兩個並使用LINQ
對結果集執行查詢。 有人告訴我,通過實現interfaces
我將能夠實現這些結果。
這是我到目前為止:
static void Main(string[] args)
{
System.Console.Write("Hello World\n");
Dog Dog1 = new Dog { name = "A", age = 1 };
Dog Dog2 = new Dog { name = "B", age = 2 };
Cat Cat1 = new Cat { name = "C", age = 3 };
Cat Cat2 = new Cat { name = "D", age = 4 };
List<Dog> DogList = new List<Dog>();
List<Cat> CatList = new List<Cat>();
DogList.Add(Dog1);
DogList.Add(Dog2);
CatList.Add(Cat1);
CatList.Add(Cat2);
var result = DogList
.Concat(CatList);
}
}
public interface iAnimal
{
string name { get; set; }
int age { get; set; }
}
public class Dog :iAnimal
{
public string name { get; set; }
public int age { get; set; }
}
public class Cat:iAnimal
{
public string name { get; set; }
public int age { get; set; }
}
我可以使用System.Console.Write(Dog1.name);
類的東西訪問我創建的任何對象的任何數據成員System.Console.Write(Dog1.name);
,所以我認為我的接口實現是正確的。 我的LINQ語句需要更改什么才能有效地Concat / Union我的列表。
我對C#
和面向對象編程很新,所以請根據我的知識水平來滿足你的答案。
謝謝
編輯我道歉,因為我忘記包含我在當前代碼中得到的錯誤消息。
Error 1 'System.Collections.Generic.List<InterfaceTest.Dog>' does not contain a definition for 'Concat' and the best extension method overload 'System.Linq.ParallelEnumerable.Concat<TSource>(System.Linq.ParallelQuery<TSource>, System.Collections.Generic.IEnumerable<TSource>)' has some invalid arguments
Error 2 Instance argument: cannot convert from 'System.Collections.Generic.List<InterfaceTest.Dog>' to 'System.Linq.ParallelQuery<InterfaceTest.Cat>'
問題是編譯器無法通過連接List<Dog>
和List<Cat>
它應該生成iAnimal
的集合。 默認情況下,它會看到List<Dog>
並期望以下集合也是Dog
的集合。
您可以通過向Concat
提供泛型參數,即明確告訴將所有內容視為iAnimal
var result = DogList.Concat<iAnimal>(CatList);
然后,您將獲得IEnumerable<iAnimal>
類型的result
。
編輯:如果你堅持使用.NET 3.5,你將需要類似的東西
var result = DogList.Cast<IAnimal>().Concat(CatList.Cast<IAnimal>());
因為3.5不能自動將collection of something that inherits iAnimal
轉換collection of something that inherits iAnimal
的collection of iAnimal
。
通用列表來自不同類型(Dog和Cat),您必須在連接之前將它們“強制轉換”到目標接口:
var list1 = DogList.Cast<IAnimal>();
var list2 = CatList.Cast<IAnimal>();
var bothLists = list1.Concat(list2); //optional .ToList()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.