I have, list Students
and Teachers
var students = new List<Student>
{
new Student
{
Id= 1,
Name = "AA",
City = "London",
Country = "UK"
},
new Student
{
Id= 2,
Name = "BB",
City = "New Orleans",
Country = "USA"
}
}
var teachers = new List<Teacher>
{
new Teacher
{
Id = 1,
Name = "CC",
City = "Berlin",
Country = "Germany"
},
new Teacher
{
Id = 2,
Name = "DD",
City = "Mexico D.F.",
Country = "Mexico"
}
}
I wanted, for each teacher, get a list of students located in the same country and the same city.
What I did so far:
var result = from teacher in teachers
select new
{
teacher,
Students = students.Where(s => s.Country == teacher.Country && s.City == teacher.City).ToList()
};
This not worked, I got casting exception
. And tried with:
var result = new List<(Teacher, IEnumerable<Student>)>();
teachers.ToList().ForEach(c => result.Add((c,
students.Where(s => s.Country == c.Country && s.City == c.City).ToList())));
This worked fine but, is there any other ways, without looping?
CodePudding user response:
Your linq query is correct. Your query returns a list of anonymous type. You cannot cast it directly to a tuple list. The problem you have is which type you are trying to cast to. If you are trying to get a result of Tuple list like IEnumerable<(Teacher, IEnumerable)> you should code as below:
var result = from teacher in teachers
select (
teacher,
students.Where(s => s.Country == teacher.Country && s.City == teacher.City).ToList()
);
Then, result.ToList() would give you a List of Tuple, result.ToArray() would give you an array of Tuple
Lambda expression alternative:
var result = teachers
.Select(teacher => (teacher, students.Where(s => s.Country == teacher.Country && s.City == teacher.City).ToList()));
However, I would prefer anonymous list as a return type rather than Tuple.