クエリの実体化を回避します。.ToList() 呼び出しを削除します。
アップデート:
class Program
{
static void Main(string[] args)
{
var Student_A = new[]{
new {StudentId = 1, Index = 23, Name = "Lucas"},
new {StudentId = 2, Index = 71, Name = "Juan"},
new {StudentId = 3, Index = 85, Name = "Noelia"}
};
var Student_B = new[]{
new {StudentId = 6, Index = 31, Name = "Marcelo"},
new {StudentId = 7, Index = 72, Name = "Manuel"},
new {StudentId = 8, Index = 95, Name = "Roberto"}
};
var StudentA = (from p in Student_A.Where(a => a.StudentId != 0)
group p by p.Index into g
select g.FirstOrDefault()).Distinct().OrderBy(a => a.Index);
var StudentB = (from p in Student_B.Where(a => a.StudentId != 0)
group p by p.Index into g
select g.FirstOrDefault()).Distinct().OrderBy(a => a.Index);
var all = StudentA.Union(StudentB);
all.ToList().ForEach(x=> Console.WriteLine(x.Name));
}
}
このスニペットとの違いはどれですか?
更新 2:
わかりました。問題は、Student_A の要素と Student_B の要素が異なる型であることです。次のようにエラーを再現できます
class Program
{
static void Main(string[] args)
{
var Student_A = new[]{
new {StudentId = 1, Index = 23, Name = "Lucas"},
new {StudentId = 2, Index = 71, Name = "Juan"},
new {StudentId = 3, Index = 85, Name = "Noelia"}
};
var Student_B = new[]{
new {StudentId = 6, Index = 31, Name = "Marcelo", I=0}, // extra property
new {StudentId = 7, Index = 72, Name = "Manuel", I=0},
new {StudentId = 8, Index = 95, Name = "Roberto", I=0}
};
var StudentA = (from p in Student_A.Where(a => a.StudentId != 0)
group p by p.Index into g
select g.FirstOrDefault()).Distinct().OrderBy(a => a.Index);
var StudentB = (from p in Student_B.Where(a => a.StudentId != 0)
group p by p.Index into g
select g.FirstOrDefault()).Distinct().OrderBy(a => a.Index)
var all = StudentA.Union(StudentB);
all.ToList().ForEach(x=> Console.WriteLine(x.Name));
}
ただし、両方を同じ型で作成すると機能します。次の例を見てください。
class Program
{
static void Main(string[] args)
{
var Student_A = new[]{
new {StudentId = 1, Index = 23, Name = "Lucas"},
new {StudentId = 2, Index = 71, Name = "Juan"},
new {StudentId = 3, Index = 85, Name = "Noelia"}
};
var Student_B = new[]{
new {StudentId = 6, Index = 31, Name = "Marcelo", I=0},
new {StudentId = 7, Index = 72, Name = "Manuel", I=0},
new {StudentId = 8, Index = 95, Name = "Roberto", I=0}
};
var StudentA = (from p in Student_A.Where(a => a.StudentId != 0)
group p by p.Index into g
select g.FirstOrDefault()).Distinct().OrderBy(a => a.Index)
.Select(x=> new {StudentId = x.StudentId, Index = x.Index, Name = x.Name });
var StudentB = (from p in Student_B.Where(a => a.StudentId != 0)
group p by p.Index into g
select g.FirstOrDefault()).Distinct().OrderBy(a => a.Index)
.Select(x=> new {StudentId = x.StudentId, Index = x.Index, Name = x.Name });
var all = StudentA.Union(StudentB);
all.ToList().ForEach(x=> Console.WriteLine(x.Name));
}
違いは次の行にあります。
.Select(x=> new {StudentId = x.StudentId, インデックス = x.Index, 名前 = x.Name });