2014-01-21 85 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();