Linq의 목록에서 여러 필드 선택
ASP.NET C #에는 구조체가 있습니다.
public struct Data
{
public int item1;
public int item2;
public int category_id;
public string category_name;
}
그 목록이 있습니다. 내가 선택하려는 category_id
및 category_name
실행, DISTINCT
그리고 마지막으로 ORDERBY
에를 category_name
.
여기 내가 지금 가진 것입니다 :
List<Data> listObject = getData();
string[] catNames = listObject
.Select(i=> i.category_name)
.Distinct()
.OrderByDescending(s => s)
.ToArray();
이것은 분명히 카테고리 이름을 얻습니다. 내 질문은 여러 필드를 얻는 방법이며 이것을 (가 아닌 string[]
) 어떤 데이터 구조에 저장 합니까?
편집하다
구조체 목록을 사용하는 것은 돌로 설정되어 있지 않습니다. 선택하기 쉽도록 백업 데이터 구조를 변경하는 것이 좋습니다 (많은 글을 쓸 것입니다). 나는 기꺼이 권장 사항을 취할 것입니다.
익명 형식을 사용하면 나중에 코드에서 강력하게 형식화 된 데이터 구조로 임의의 필드를 선택할 수 있습니다.
var cats = listObject
.Select(i => new { i.category_id, i.category_name })
.Distinct()
.OrderByDescending(i => i.category_name)
.ToArray();
나중에 사용하기 위해 저장해야하므로 GroupBy 연산자를 사용할 수 있습니다.
Data[] cats = listObject
.GroupBy(i => new { i.category_id, i.category_name })
.OrderByDescending(g => g.Key.category_name)
.Select(g => g.First())
.ToArray();
var selectedCategories =
from value in
(from data in listObject
orderby data.category_name descending
select new { ID = data.category_id, Name = data.category_name })
group value by value.Name into g
select g.First();
foreach (var category in selectedCategories) Console.WriteLine(category);
편집 : 더 LINQ-ey로 만들었습니다!
익명 유형을 사용할 수 있습니다.
.Select(i => new { i.name, i.category_name })
컴파일러와 클래스에 대한 코드 생성 name
및 category_name
해당 클래스의 속성과 반환 인스턴스를. 속성 이름을 수동으로 지정할 수도 있습니다.
i => new { Id = i.category_id, Name = i.category_name }
임의의 수의 속성을 가질 수 있습니다.
이하는 일이다 익명 형식이 매우 적합하다. 사용법에서 유추하여 컴파일러가 자동으로 생성 한 유형의 객체를 반환 할 수 있습니다.
구문은 다음과 같은 형식입니다.
new { Property1 = value1, Property2 = value2, ... }
귀하의 경우 다음과 같은 것을 시도하십시오.
var listObject = getData();
var catNames = listObject.Select(i =>
new { CatName = i.category_name, Item1 = i.item1, Item2 = i.item2 })
.Distinct().OrderByDescending(s => s).ToArray();
var result = listObject.Select( i => new{ i.category_name, i.category_id } )
익명 형식을 사용하므로 식의 결과 형식을 미리 알 수 없으므로 var 키워드를 사용해야합니다.
(from i in list
select new { i.category_id, i.category_name })
.Distinct()
.OrderBy(i => i.category_name);
You can select multiple fields using linq Select as shown above in various examples this will return as an Anonymous Type. If you want to avoid this anonymous type here is the simple trick.
var items = listObject.Select(f => new List<int>() { f.Item1, f.Item2 }).SelectMany(item => item).Distinct();
I think this solves your problem
You can make it a KeyValuePair, so it will return a "IEnumerable<KeyValuePair<string, string>>"
So, it will be like this:
.Select(i => new KeyValuePair<string, string>(i.category_id, i.category_name )).Distinct();
public class Student
{
public string Name { set; get; }
public int ID { set; get; }
}
class Program
{
static void Main(string[] args)
{
Student[] students =
{
new Student { Name="zoyeb" , ID=1},
new Student { Name="Siddiq" , ID=2},
new Student { Name="sam" , ID=3},
new Student { Name="james" , ID=4},
new Student { Name="sonia" , ID=5}
};
var studentCollection = from s in students select new { s.ID , s.Name};
foreach (var student in studentCollection)
{
Console.WriteLine(student.Name);
Console.WriteLine(student.ID);
}
}
}
참고URL : https://stackoverflow.com/questions/1202981/select-multiple-fields-from-list-in-linq
'Programing' 카테고리의 다른 글
리눅스에서 정적 라이브러리를 컴파일하는 방법? (0) | 2020.07.08 |
---|---|
number (x) 또는 parseFloat (x) 중 어느 것이 더 낫습니까? (0) | 2020.07.08 |
MySQL의 CHECK 제약 조건이 작동하지 않습니다 (0) | 2020.07.08 |
Tensorflow 디버깅 정보 비활성화 (0) | 2020.07.08 |
프로그래밍 방식으로 "누가 Zebra를 소유하고 있습니까?" (0) | 2020.07.08 |