2016-08-04 36 views
1

myTuples有{string id, int start, int end}自聯接LINQ與不等於

有了這個樣本數據:

{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 
}; 
+0

http://stackoverflow.com/questions/3762869/is-there-a-not-equal-in-a-linq-join –

+0

@MauriceReeves的可能重複不知道是否重複,因爲在那種情況下,他希望'groupA MINUS groupB'我想要'groupA CROSS JOIN groupA' –

回答

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) 
}) 
+0

謝謝,如果我的查詢與您的查詢相同,有何想法? –

+0

是的。謝謝 – 2016-08-04 18:29:15

+0

在您的查詢什麼是'Item1'?一些默認名稱,因爲你沒有命名屬性? –

0

莫里斯評論後,意識到我搜索錯誤的問題。 Im做CROSS JOININNER JOIN

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