LINQ의 Noob, 동일한 값으로 각 레코드의 첫 번째 레코드를 선택
-
03-07-2019 - |
문제
나는 LINQ를 배우기 위해 최선을 다하고 있지만 여전히 그것을 코딩하는 데 어려움을 겪고 있습니다. 이와 마찬가지로, 데이터 세트 나 목록이있을 수 있으며 컬렉션 객체의 이름 또는 필드가 열 이름이라고 가정합니다.
id | 날짜 | 월 | 화 | 수
1 | 01/05 |=1=|==1==|==1=|==1=| 1=|=0=|=0==|==5 <-- (1)
2 | 02/02 |=1=|==1==|==1=|==1=| 1=|=0=|=0==|==5 **|-- (2)
3 | 03/02 |=1=|==1==|==1=|==1=| 1=|=0=|=0==|==5 **|-- (2)
4 | 04/06 |=1=|==1==|==1=|==1=| 1=|=1=|=1==|==7 <-- (1)
5 | 05/04 |=1=|==1==|==1=|==1=| 1=|=1=|=1==|==7 **|-- (3)
6 | 06/01 |=1=|==1==|==1=|==1=| 1=|=1=|=1==|==7 **|-- (3)
7 | 07/06 |=1=|==1==|==1=|==1=| 0=|=0=|=0==|==4 <---- (1)
8 | 08/03 |=1=|==1==|==1=|==1=| 0=|=0=|=0==|==4 **|-- (4)
9 | 09/07 |=1=|==1==|==1=|==1=| 0=|=0=|=0==|==4 **|-- (4)
10 | 10/05 |1=|==1==|==1=|==1=| 0=|=0=|=0==|==4 **|-- (4)
내가 원하는 것은 먼저 (1)의 모든 숫자를 얻는 것입니다. 다음으로 (3)의 그룹은 두 번째 (1)에 속하기 때문입니다. 마지막 (4)의 그룹은 마지막 (1)에 속하기 때문입니다.
도와주세요.
- 질문이 다시 게시되었습니다. 1. 어떻게 5의 첫 번째 그룹을 얻을 수 있고 7의 그룹과 4의 그룹을 마지막으로 얻을 수 있습니까?
해결책
카운트별로 주문하고 싶어하는 것 같습니다.
"5의 첫 번째 그룹"을 말할 때 무엇을 의미합니까? 어떤 데이터를 얻고 싶습니까?
업데이트 설명 후
가정합니다
public class Row
{
public int ID{get;set;}
public string Date{get;set;}
public int Count{get;set;}
}
Row r1 = new Row{ID=1, Date="01/01/01", Count=5};
Row r2 = new Row{ID=2, Date="01/02/01", Count=5};
Row r3 = new Row{ID=3, Date="01/03/01", Count=5};
Row r4 = new Row{ID=4, Date="01/04/01", Count=7};
Row r5 = new Row{ID=5, Date="01/05/01", Count=7};
Row r6 = new Row{ID=6, Date="01/06/01", Count=7};
Row r7 = new Row{ID=7, Date="01/07/01", Count=4};
Row r8 = new Row{ID=8, Date="01/08/01", Count=4};
Row r9 = new Row{ID=9, Date="01/09/01", Count=4};
Row r10 = new Row{ID=10, Date="01/01/01", Count=4};
List<Row> rows = new List<Row>{r1,r2,r3,r4,r5,r6,r7,r8,r9,r10};
그 다음에
// We will assign results of our query to this variable
var result =
// rows is a generic list of Row objects
rows
// This splits the list into seperate categories organised by Count
// After the GroupBy, we have an IEnumerable<IGrouping<Int32, Row>> - that is, a collection of collections of items sharing a common key (in this case Count)
.GroupBy(r=>r.Count) // r is of type Row
// Now we are simply selecting the first item of each subgroup.
.Select(g=>g.First()) // g is IGrouping<Int32,Row>, g.First() is of type Row
;
주어진
ID Date Count
1 01/01/01 5
4 01/04/01 7
7 01/07/01 4