我正在尝试在两个集合之间进行左连接。在图像中显示的结果中,我希望只看到一次 Anand。我究竟做错了什么
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqJoin
{
internal class MainClass
{
public static void Main(string[] args)
{
var chessPlayers = new List<ChessPlayer>
{
new ChessPlayer {FirstName = "Anand", Age = 51},
new ChessPlayer {FirstName = "Bobby", Age = 77},
new ChessPlayer {FirstName = "Kasprov", Age = 64}
};
var compScientists = new List<ComputerScientist>
{
new ComputerScientist {FirstName = "Anand", Language = "C++"},
new ComputerScientist {FirstName = "Anand", Language = "C#"},
new ComputerScientist {FirstName = "Bobby", Language = "Java"},
new ComputerScientist {FirstName = "Steve", Language = "Ruby"},
};
var leftJoin =
from ch in chessPlayers
join cs in compScientists on ch.FirstName equals cs.FirstName
into chcs
from cs in chcs.DefaultIfEmpty()
select new {chessPlayer = ch, comp = chcs};
foreach (var left in leftJoin)
{
Console.WriteLine("*********************");
Console.WriteLine("{0} {1} ", left.chessPlayer.FirstName, left.chessPlayer.Age);
foreach (ComputerScientist right in left.comp)
{
Console.WriteLine("\t" + right.Language);
}
}
}
}
internal class ChessPlayer
{
public string FirstName { get; set; }
public int Age { get; set; }
}
internal class ComputerScientist
{
public string FirstName { get; set; }
public string Language { get; set; }
}
}