当底层匿名类型相似时,如何在Linq中连接两个列表
本文关键字:连接 Linq 列表 两个 类型 相似 | 更新日期: 2023-09-27 17:54:59
考虑以下代码:
var listA = from s in Students
select new {FirstName= s.FirstName, LastName = s.LastName};
var listB = from t in Teachers
select new {FirstName= t.FirstName, LastName = t.LastName};
var teachersAndStudents = listA.Concat(listB); // This fails because types are not same
var someName = teachersAndStudents.First().FirstName;
如何创建teachersAndStudents
列表而不丢失类型?
不丢失类型意味着teachersAndStudents.First().FirstName
应该在最后一行有效。
这段代码运行良好,你的问题在别的地方
class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Teacher
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Program
{
static void Main(string[] args)
{
var listA = from s in new List<Student>()
select new { FirstName = s.FirstName, LastName = s.LastName };
var listB = from t in new List<Teacher>()
select new { FirstName = t.FirstName, LastName = t.LastName };
var teachersAndStudents = listA.Concat(listB);
var someName = teachersAndStudents.First().FirstName;
}
}
调用Concat的行不会因为类型而失败,因为两个匿名类型是相同的。试试这段代码,你也会看到:
var listA = from s in Students
select new { FirstName = s.FirstName, LastName = s.LastName };
var listB = from t in Teachers
select new { FirstName = t.FirstName, LastName = t.LastName };
Console.WriteLine(listA.First().GetType().Name);
Console.WriteLine(listB.First().GetType().Name);
在我的例子中,这段代码输出:
<>f__AnonymousType0`2
<>f__AnonymousType0`2
这证明编译器已经为要求匿名类型的语句生成了相同的实际类型。
你能附加你收到的错误吗?