当底层匿名类型相似时,如何在Linq中连接两个列表?

时间:2015-06-10 08:15:11

标签: c# linq

考虑以下代码:

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应该在最后一行有效。

2 个答案:

答案 0 :(得分:6)

此代码运行良好,您的问题在其他方面

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

答案 1 :(得分:3)

调用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

这证明编译器为需要匿名类型的语句生成了相同的实际类型。

您能否附上您正在接收的错误?