여러 열을 기준으로 그룹화
LINQ에서 여러 열을 기준으로 그룹화하려면 어떻게 해야 합니까?
SQL에서 이와 유사한 내용:
SELECT * FROM <TableName> GROUP BY <Column1>,<Column2>
LINQ로 변환하려면 어떻게 해야 합니까?
QuantityBreakdown
(
MaterialID int,
ProductID int,
Quantity float
)
INSERT INTO @QuantityBreakdown (MaterialID, ProductID, Quantity)
SELECT MaterialID, ProductID, SUM(Quantity)
FROM @Transactions
GROUP BY MaterialID, ProductID
익명 형식을 사용합니다.
에그
group x by new { x.Column1, x.Column2 }
절차 샘플:
.GroupBy(x => new { x.Column1, x.Column2 })
좋아요, 다음과 같이 받았습니다.
var query = (from t in Transactions
group t by new {t.MaterialID, t.ProductID}
into grp
select new
{
grp.Key.MaterialID,
grp.Key.ProductID,
Quantity = grp.Sum(t => t.Quantity)
}).ToList();
여러 열로 그룹화의 경우 대신 시도...
GroupBy(x=> new { x.Column1, x.Column2 }, (key, group) => new
{
Key1 = key.Column1,
Key2 = key.Column2,
Result = group.ToList()
});
3열, 4열 등을 추가할 수 있는 것과 동일한 방법입니다.
C# 7에서는 값 튜플도 사용할 수 있습니다.
group x by (x.Column1, x.Column2)
또는
.GroupBy(x => (x.Column1, x.Column2))
C# 7.1 이상 사용Tuples
그리고.Inferred tuple element names
(현재는 에서만 작동합니다.linq to objects
식 트리가 필요한 경우에는 지원되지 않습니다. someIQueryable.GroupBy(...)
Github 이슈):
// declarative query syntax
var result =
from x in inMemoryTable
group x by (x.Column1, x.Column2) into g
select (g.Key.Column1, g.Key.Column2, QuantitySum: g.Sum(x => x.Quantity));
// or method syntax
var result2 = inMemoryTable.GroupBy(x => (x.Column1, x.Column2))
.Select(g => (g.Key.Column1, g.Key.Column2, QuantitySum: g.Sum(x => x.Quantity)));
C# 3 이상 사용anonymous types
:
// declarative query syntax
var result3 =
from x in table
group x by new { x.Column1, x.Column2 } into g
select new { g.Key.Column1, g.Key.Column2, QuantitySum = g.Sum(x => x.Quantity) };
// or method syntax
var result4 = table.GroupBy(x => new { x.Column1, x.Column2 })
.Select(g =>
new { g.Key.Column1, g.Key.Column2 , QuantitySum= g.Sum(x => x.Quantity) });
강력한 유형의 그룹에 Tuple<>을 사용할 수도 있습니다.
from grouping in list.GroupBy(x => new Tuple<string,string,string>(x.Person.LastName,x.Person.FirstName,x.Person.MiddleName))
select new SummaryItem
{
LastName = grouping.Key.Item1,
FirstName = grouping.Key.Item2,
MiddleName = grouping.Key.Item3,
DayCount = grouping.Count(),
AmountBilled = grouping.Sum(x => x.Rate),
}
이 질문은 클래스별 그룹 속성에 대한 질문이지만 ADO 개체(예: DataTable)에 대해 여러 열로 그룹화하려면 변수에 "새" 항목을 할당해야 합니다.
EnumerableRowCollection<DataRow> ClientProfiles = CurrentProfiles.AsEnumerable()
.Where(x => CheckProfileTypes.Contains(x.Field<object>(ProfileTypeField).ToString()));
// do other stuff, then check for dups...
var Dups = ClientProfiles.AsParallel()
.GroupBy(x => new { InterfaceID = x.Field<object>(InterfaceField).ToString(), ProfileType = x.Field<object>(ProfileTypeField).ToString() })
.Where(z => z.Count() > 1)
.Select(z => z);
var Results= query.GroupBy(f => new { /* add members here */ });
주의할 점은 람다 식에 대한 개체를 보내야 하고 클래스에 인스턴스를 사용할 수 없다는 것입니다.
예:
public class Key
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
이렇게 하면 컴파일되지만 사이클당 하나의 키가 생성됩니다.
var groupedCycles = cycles.GroupBy(x => new Key
{
Prop1 = x.Column1,
Prop2 = x.Column2
})
키 속성의 이름을 지정하고 검색하지 않으려면 대신 이렇게 수행할 수 있습니다.이 의지GroupBy
정확하게 입력하고 주요 속성을 클릭합니다.
var groupedCycles = cycles.GroupBy(x => new
{
Prop1 = x.Column1,
Prop2= x.Column2
})
foreach (var groupedCycle in groupedCycles)
{
var key = new Key();
key.Prop1 = groupedCycle.Key.Prop1;
key.Prop2 = groupedCycle.Key.Prop2;
}
x를 새 {x}로 그룹화합니다.색상, x.Col}
.GroupBy(x => (x.MaterialID, x.ProductID))
.GroupBy(x => x.Column1 + " " + x.Column2)
VB 및 익명/람다의 경우:
query.GroupBy(Function(x) New With {Key x.Field1, Key x.Field2, Key x.FieldN })
언급URL : https://stackoverflow.com/questions/847066/group-by-multiple-columns
'programing' 카테고리의 다른 글
'git checkout'을 'gitco'에 별칭을 붙이는 방법 (0) | 2023.06.30 |
---|---|
Docker에서 Wordpress로 게시물을 저장할 수 없습니다. (0) | 2023.06.30 |
java.sql.SQL 예외:oracle.jdbc.driver에 설정된 자동 커밋으로 커밋할 수 없습니다.PhysicalConnection.commit(PhysicalConnection.java:4443) (0) | 2023.06.30 |
MariaDB ROW_NUMBER(주문 번호 포함)가 올바르게 주문되지 않음 (0) | 2023.06.30 |
IIS에서 스레드를 사용하여 장시간 실행 작업을 수행할 수 있습니까? (0) | 2023.06.30 |