【问题标题】:Self JOIN linq with not equal自 JOIN linq 不等于
【发布时间】:2016-12-10 22:26:13
【问题描述】:

myTuples 有 {string id, int start, int end}

使用此示例数据:

{A, 10, 11}, 
{B, 20, 30}, 
{C, 25, 35}, 
{D, 25, 28}, 
{E,  7, 35},

结果应该是:x1 < x2 < x3 < x4

{7,  10, 11, 35} -- row id=A {10, 11} between id=E {7,35}
{7,  25, 28, 35} -- row id=D {25, 28} between id=E {7,35}
{20, 25, 28, 30} -- row id=D {25, 28} between id=B {20,30}

如果您添加{F, 15, 40},那么row=B 也可以在里面。

{15, 20, 30, 40} -- row id=B {20, 30} between id=F {15,40}

这是我尝试过的。

var query = from t1 in myTuples
            join t2 in myTuples
                 on t1.id equals t2.id
            where (t1.start > t2.start && t1.end < t2.end)
               || (t1.start < t2.start && t1.end > t2.end)
            select new
            {
                x1 = t1.start,
                x2 = t2.start,
                x3 = t1.end, 
                x4 = t2.end
            };

但我的第一个问题是没有not equal 加入。

最后一部分无关紧要,我可以稍后修复它。但我想像

 select new
 {
   x1 = t1.start < t2.start : t1.start : t2.start,
   x2 = t1.start < t2.start : t2.start : t1.start,
   x3 = t1.end < t2.en: t1.end: t2.end,
   x4 = t1.end < t2.en: t2.end: t1.end
 };

【问题讨论】:

标签: c# linq


【解决方案1】:

已定义

 var myTuples = new Tuple<string,int,int>[5] {
new Tuple<string,int,int>("A",10,11), new Tuple<string,int,int>("B",20,30),
new Tuple<string,int,int>("C",25,35), new Tuple<string,int,int>("D",25,28),
new Tuple<string,int,int>("E",7,35) };

我可以使用 SelectMany 进行不相等的自联接。

     var selfJoinNotEqual = myTuples
.SelectMany( x => myTuples.Where(y => y.Item1 != x.Item1).Select( y => new { x, y}));

对于第二部分,添加另一个选择

.Select(z => new {  
    x1 = ( z.x.Item2 <= z.y.Item2 ? z.x.Item2 : z.y.Item2),
    x2 = (z.x.Item2 <= z.y.Item2 ? z.y.Item2 : z.x.Item2) ,
    x3 = (z.x.Item3 <= z.y.Item3 ? z.x.Item3 : z.y.Item3),
    x4 = (z.x.Item3 <= z.y.Item3 ? z.y.Item3 : z.x.Item3) 
})

【讨论】:

  • 谢谢,您知道我的查询是否与您的相同吗?
  • 是的。谢谢
  • 在您的查询中,Item1 是什么?一些默认名称,因为您没有命名属性?
  • 是你的id,Tuple的第一项,Item2是start,Item3是end。我使用了默认值
【解决方案2】:

对莫里斯发表评论后,意识到我搜索了错误的问题。我在做CROSS JOIN 而不是INNER JOIN

var combo = from t1 in myTuples
            from t2 in myTuples
            where
               t1.id < t2.id
            select new { t1, t2 };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 2016-10-31
    • 2015-03-07
    • 2011-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多