from x in myCollection
group x by x.Id into y
select new {
Id = y.Key,
Quantity = y.Sum(x => x.Quantity)
};
위의 내용을 람다 식으로 작성하면 어떻습니까? 나는 group into
부분에 붙어 있습니다.람다 식의 GroupBy
from x in myCollection
group x by x.Id into y
select new {
Id = y.Key,
Quantity = y.Sum(x => x.Quantity)
};
위의 내용을 람다 식으로 작성하면 어떻습니까? 나는 group into
부분에 붙어 있습니다.람다 식의 GroupBy
쿼리 연속성을가 (에 ...에 그룹 ... 선택할 수 있지만 하지 가입 ...로)은 단지 쿼리 식을 분할에 해당합니다. 점 표기법에 사람들은
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 자체를 모두 다루는 것으로 보입니다.
아마도 이것이 주요 용도 일지 모르지만. 내 요구를 정말로 만족시키지 못했습니다.
내 경우에는 기본적으로 개체 속성별로 그룹화 한 다음 해당 그룹에서 특정 개체를 가져 오려고했습니다. 다음은 샘플 코드입니다. 당신이 오히려 foreach 루프를 사용한다면
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; }
}
}
(나는 쉽게 읽을 발견하면 나는 람다를 선호),하지만 당신이 할 경우, 당신과 같이 그것을 할 수 있습니다.
희망이 있으면 도움이 될 것입니다. :)
이 답변의 역할과 해당 문제에 대한 해결책을 설명하는 텍스트를 추가해야합니다. 코드 덤프는 다른 사람에게 거의 사용되지 않습니다. –