from x in myCollection
group x by x.Id into y
select new {
Id = y.Key,
Quantity = y.Sum(x => x.Quantity)
};
您會如何將上述內容寫入lambda表達式?我卡在group into
部分。GroupBy在lambda表達式中
from x in myCollection
group x by x.Id into y
select new {
Id = y.Key,
Quantity = y.Sum(x => x.Quantity)
};
您會如何將上述內容寫入lambda表達式?我卡在group into
部分。GroupBy在lambda表達式中
查詢延續(SELECT ... INTO和組...成,但不加入...進入)等價於剛分手了查詢表達式。所以我喜歡把你的例子爲:
var tmp = from x in myCollection
group x by x.Id;
var result = from y in tmp
select new {
Id = y.Key,
Quantity = y.Sum(x => x.Quantity)
};
改變那些進入點符號:
var tmp = myCollection.GroupBy(x => x.Id);
var result = tmp.Select(y => new {
Id = y.Key,
Quantity = y.Sum(x => x.Quantity)
});
然後,你可以將它們合併回:
var tmp = myCollection.GroupBy(x => x.Id)
.Select(y => new {
Id = y.Key,
Quantity = y.Sum(x => x.Quantity)
});
一旦你的工作是什麼C#編譯器使用查詢表達式,其餘部分相對簡單:)
myCollection
.GroupBy(x => x.Id)
.Select(x =>
new
{
Id = x.Key,
Quantity = x.Sum(y => x.Quantity
});
myCollection.GroupBy(x => x.Id)
.Select(y => new {
Id = y.Key,
Quantity = y.Sum(x => x.Quantity)
});
var mostFrequent =
lstIn.Where(i => !string.IsNullOrEmpty(i))
.GroupBy(s => s)
.OrderByDescending(g => g.Count())
.Select(s => s.Key)
.FirstOrDefault();
因此,對於這裏的大多數答案,每個人似乎都在處理從組的計數中獲取Id的簡單對象,以及作爲group.Key的Key本身。
雖然這可能是這個主要用途。沒有真正滿足我的需求。
對於我自己的情況,我基本上想通過某些對象屬性進行分組,然後從該組中獲取特定對象。這是一個示例代碼。
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
var response = new List<ResponseClass>();
var listOfStudents = new List<Student>();
// Insert some objects into listOfStudents object.
listOfStudents.GroupBy(g => g.Class).ToList()
.ForEach(g => response.Add(g.OrderByDescending(s => s.CreatedOn).Select(a =>
new ResponseClass
{
SName = a.StudentName,
SAge = a.Age,
SClass = a.Class,
SCreatedOn = a.CreatedOn,
RandomProperty = Guid.NewGuid().ToString()
})
.First()));
Console.WriteLine("This compiles and should work just fine");
}
class Student
{
public string StudentName { get; set; }
public int Age { get; set; }
public string Class { get; set; }
public DateTime CreatedOn { get; set; }
}
class ResponseClass
{
public string SName { get; set; }
public int SAge { get; set; }
public string SClass { get; set; }
public DateTime SCreatedOn { get; set; }
public string RandomProperty { get; set; }
}
}
如果你寧願使用foreach循環(我喜歡的λ,因爲我覺得它更容易閱讀),但是如果你這樣做,你能做到這一點,像這樣。
希望這可以幫助別人。 :)
您應該添加一些文字說明此答案的作用以及爲什麼它提供瞭解決方案的具體問題。代碼轉儲很少用於其他人。 – 2016-02-08 00:54:44