我正在尝试在Linq中将此查询转换为(Microsoft)SQL。
SELECT MAX(ID) AS MyValue
FROM Table
WHERE "list contains 1 or 2 or 3"
我该怎么做? 我看到的唯一例子只是在整个列上产生最大值而不是每个组(例如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 - &gt; where myList.Contains(MyTable.ID)
我只想在C#中为一个字符串列表选择1列。
答案 0 :(得分:2)
这样的东西?
myList = yourList.GroupBy(x => x.TogetherId)
.Select(x => x.OrderByDescending(y => y.Id).First())
.ToList();
答案 1 :(得分:2)
您会想要GroupBy
后面跟Max
:
var newList = myList.GroupBy(x => x.TogetherId, x => x.Id)
.Select(x => new {
TogetherId = x.Key,
MaxId = x.Max()
})
.ToList();
答案 2 :(得分:0)
list
.GroupBy(x => x.TogetherId)
.Select(g => new { TogetherId = g.Key, Max = g.Max(x => x.Id) });
答案 3 :(得分: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()
答案 4 :(得分: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();