【问题标题】:Linq 'join ... into' doesn't return joined objectsLinq 'join ... into' 不返回连接对象
【发布时间】:2019-05-15 16:20:38
【问题描述】:

我是 SQL 和 LINQ 的新手。我尝试了一个简单的代码来使用join...into 语法连接两个列表,但结果不是我所期望的。

public static void Main(string[] args)
{
    IEnumerable<KeyValuePair<char,int>> list1 = new []{ 
        new KeyValuePair<char,int>( 'a', 1) ,
        new KeyValuePair<char,int>( 'b', 2) , 
        new KeyValuePair<char,int>( 'c', 3)  };
    IEnumerable<KeyValuePair<char, int>> list2 =  new[]{
        new KeyValuePair<char,int>( 'b', 10) ,
        new KeyValuePair<char,int>( 'c', 20) ,
        new KeyValuePair<char,int>( 'd', 30)  };

    var joinQuery = from x in list1
                    join y in list2
                    on x.Key equals y.Key into joinTable
                    from t in joinTable
                    select new { element = t };

    foreach (var el in joinQuery)
        Console.WriteLine(el);
}

输出是:

{ element = [b, 10] }
{ element = [c, 20] }

我的预期是 joinTable 包含连接记录,例如:

{element = {[b, 2], [b, 10]}}
{element = {[c, 3], [c, 20]}}

您能解释一下... into joinTable 部分的实际作用,以及为什么我可以在最后一次选择中使用x 而我不能使用y

var joinQuery = from x in list1
                join y in list2
                on x.Key equals y.Key into joinTable
                from t in joinTable
                select new { element = t,
                             first = x,  // OK
                             second = y} // Error: The name y doesn't exist in the current context

【问题讨论】:

    标签: c# linq join linq-to-sql


    【解决方案1】:

    根据Jon Skeet's blogjoin ... into 语法被转换为GroupJoin(),而不是您所期望的Join

    但你真正想要的是一个真正的连接,所以就像这样:

    var joinQuery = from x in list1
                    join y in list2
                    on x.Key equals y.Key                     
                    select new { x, y };
    

    在您的查询中,您无法访问y,因为join into 的语法不同。您不需要另一个from... joinTable,但必须直接访问joinTable

    var joinQuery = from x in list1
                    join y in list2
                    on x.Key equals y.Key into joinTable
                    select new {joinTable.x, matches = joinTable.y.ToList()};
    

    但这会导致y 拥有来自list2所有匹配 元素。这就是Join(导致每个匹配元素有一个“行”)和GroupJoin(匹配组合在一起)之间的区别。

    【讨论】:

      【解决方案2】:

      如果我理解正确,您基本上是在尝试从列表 1 和列表 2 中获取它们在键上匹配的所有信息。如果是这样,您可以这样做:

      var joinQuery = from x in list1
                      join y in list2
                      on x.Key equals y.Key
                      select new
                      {
                          first = x,
                          second = y
                      };
      

      您不需要将它添加到任意表中,只需从连接的结果中选择即可。

      【讨论】:

      • 我知道我可以做到这一点。我问了两个问题,为什么它不能使用 into 语法,以及为什么我没有看到 y 变量如果我使用 into 语法(在你的情况下 y 在选择下可见)跨度>
      • @Petar - 我的错误。我以为你在问为什么你不能得到你想要的结果,是因为与“进入”有关
      猜你喜欢
      • 2014-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-27
      • 2017-04-02
      • 2015-01-12
      • 2013-10-20
      • 1970-01-01
      相关资源
      最近更新 更多