自我加入linq并不相等

时间:2016-08-04 17:03:02

标签: c# linq

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
 };

2 个答案:

答案 0 :(得分: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) 
})

答案 1 :(得分:0)

在评论莫里斯后,意识到我在寻找错误的问题。我在做CROSS JOIN而不是INNER JOIN

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