这个当前项目更像是一个更大项目的概念证明.我有两个"表"(表示为下面的列表),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; }
}
Run Code Online (Sandbox Code Playgroud)
我可以使用类似的东西访问我创建的任何对象的任何数据成员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>'
Run Code Online (Sandbox Code Playgroud)
Raw*_*ing 13
问题是编译器无法弄清楚通过连接a List<Dog>和a List<Cat>它应该产生一个iAnimals 的集合.默认情况下,它会看到a List<Dog>并期望以下集合也是一个集合Dog.
您可以iAnimal通过提供泛型参数Concat,即明确告诉将所有内容视为此
var result = DogList.Concat<iAnimal>(CatList);
Run Code Online (Sandbox Code Playgroud)
然后你得到一个result类型IEnumerable<iAnimal>.
编辑:如果你坚持使用.NET 3.5,你将需要类似的东西
var result = DogList.Cast<IAnimal>().Concat(CatList.Cast<IAnimal>());
Run Code Online (Sandbox Code Playgroud)
因为3.5无法自动转换collection of something that inherits iAnimal为collection of iAnimal.
| 归档时间: |
|
| 查看次数: |
2957 次 |
| 最近记录: |