Linq左连接,左边的集合项在结果中重复

时间:2013-10-16 18:46:11

标签: c# linq

我正在尝试在两个集合之间进行左连接。在图像中显示的结果中,我期待只看到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; }
    }
}

enter image description here

2 个答案:

答案 0 :(得分:2)

你没有做错任何事情,如果连接条件匹配每个有问题的行,左连接将返回多行。

考虑左连接的最佳方法只是一个内连接,在右表上返回带有空值的非匹配行。

我认为你想要的是不同的清单。在这种情况下,您将要更改

 foreach (var left in leftJoin)

foreach (var left in leftJoin.Distinct())

答案 1 :(得分:1)

你显然想要GroupJoin而不是LeftJoin。

var query =
  from ch in chessPlayers
  join cs in compScientists on ch.FirstName equals cs.FirstName
    into g
  select new {chessPlayer = ch, comp = g.ToList()};