2014-01-21 121 views
0

我試圖在Linq中將此查詢轉換爲(Microsoft)SQL。列表<int>:Linq獲取每個項目的列表

SELECT  MAX(ID) AS MyValue 
FROM   Table 
WHERE "list contains 1 or 2 or 3" 

我該怎麼做? 我看到周圍的唯一實施例僅導致在整個列中的max和不每組(實施例其中TogetherId = 1)

我想獲得像結果: 行數:

TogetherId | Id 
1 | 1 
1 | 2 
1 | 16 
2 | 7 
3 | 8 
3 | 9 

結果:

TogetherId | Id 
1 | 16 
2 | 7 
3 | 9 

我如何能做到這一點的LINQ?

List<int> myList; // Consider the list to be populated. 

我已經使用這一塊的地方 - >where myList.Contains(MyTable.ID)

我只是要選擇1列至一個字符串列表在C#中。

回答

2

是這樣的?

myList = yourList.GroupBy(x => x.TogetherId) 
       .Select(x => x.OrderByDescending(y => y.Id).First()) 
       .ToList(); 
0
list 
.GroupBy(x => x.TogetherId) 
.Select(g => new { TogetherId = g.Key, Max = g.Max(x => x.Id) }); 
2

你會希望像一個GroupBy後跟一個Max

var newList = myList.GroupBy(x => x.TogetherId, x => x.Id) 
      .Select(x => new { 
        TogetherId = x.Key, 
        MaxId = x.Max() 
      }) 
      .ToList(); 

活生生的例子:http://rextester.com/LROWSF91311

0

和變異與查詢語法

myList = (from x in yourList 
     group x by x.TogetherId into g 
     select new { 
      TogetherId = g.Key, 
      Max = g.Max(a=>a.Id) 
     }).ToList() 
0
List<int> myList = new List<int>(); 
myList.Add(1); 
myList.Add(2); 

List<String> myList1 = MyTable.Where(x=> myList.Contains(x.TogetherId)).GroupBy(x => x.TogetherId) 
          .Select(x => Convert.ToString(x.OrderByDescending(y => y.Id).First().Id)) 
          .ToList();