LINQ select 문 내부에서 변수를 사용하려고합니다.LINQ 이름으로 속성 선택
다음은 현재 내가하고있는 일례입니다.
using System;
using System.Collections.Generic;
using System.Linq;
using Faker;
namespace ConsoleTesting
{
internal class Program
{
private static void Main(string[] args)
{
List<Person> listOfPersons = new List<Person>
{
new Person(),
new Person(),
new Person(),
new Person(),
new Person(),
new Person(),
new Person(),
new Person(),
new Person(),
new Person(),
new Person()
};
var firstNames = Person.GetListOfAFirstNames(listOfPersons);
foreach (var item in listOfPersons)
{
Console.WriteLine(item);
}
Console.WriteLine();
Console.ReadKey();
}
public class Person
{
public string City { get; set; }
public string CountryName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Person()
{
FirstName = NameFaker.Name();
LastName = NameFaker.LastName();
City = LocationFaker.City();
CountryName = LocationFaker.Country();
}
public static List<string> GetListOfAFirstNames(IEnumerable<Person> listOfPersons)
{
return listOfPersons.Select(x => x.FirstName).Distinct().OrderBy(x => x).ToList();
}
public static List<string> GetListOfCities(IEnumerable<Person> listOfPersons)
{
return listOfPersons.Select(x => x.FirstName).Distinct().OrderBy(x => x).ToList();
}
public static List<string> GetListOfCountries(IEnumerable<Person> listOfPersons)
{
return listOfPersons.Select(x => x.FirstName).Distinct().OrderBy(x => x).ToList();
}
public static List<string> GetListOfLastNames(IEnumerable<Person> listOfPersons)
{
return listOfPersons.Select(x => x.FirstName).Distinct().OrderBy(x => x).ToList();
}
}
}
}
I합니다 ... GetListOf와 매우 건조하지 코드가 방법
내가이
public static List<string> GetListOfProperty(
IEnumerable<Person> listOfPersons, string property)
{
return listOfPersons.Select(x =>x.property).Distinct().OrderBy(x=> x).ToList();
}
같은 것을 할 수 있어야하지만이 유 효하지 않습니다 같은 느낌 암호. 키가 Func을 만드는 것과 관련이 있다고 생각합니다.
이것이 답변 인 경우 어떻게합니까?
여기 refelection을 사용하는 두 번째 시도가 있습니다. 그러나 이것은 또한 아무 것도 아닙니다.
public static List<string> GetListOfProperty(IEnumerable<Person>
listOfPersons, string property)
{
Person person = new Person();
Type t = person.GetType();
PropertyInfo prop = t.GetProperty(property);
return listOfPersons.Select(prop).Distinct().OrderBy(x =>
x).ToList();
}
은 내가 원기 회복이 데드 엔드/훈제 청어 수 있습니다 생각하지만 난 어쨌든 내 작품을 보여줄 거라 생각 했어요.
참고 샘플 코드가 단순화되었지만 datalist을 AJAX를 통해 채우는 데 사용되어 자동 완성 경험을 생성합니다. 그 객체는 20 개 이상의 속성을 가지고 있으며 20 개 이상의 메소드를 작성하여 완료 할 수 있지만 이것을 완료하려면 DRY 방법이 있어야한다고 생각합니다. 또한이 한 가지 방법을 사용하면 컨트롤러 동작을 한꺼번에 정리할 수도 있습니다.
질문 : 코드의 첫 번째 섹션을 감안할 때
이 하나의 방법으로 그 유사한 방법 SELECT 문에 일부 개체를 전달 살 추상에 방법이 ???
감사합니다.
당신은 코드를 보여주는뿐만 아니라 단어의 질문을 진술 수 있을까요? – Crowcoder
DV GetProperty()를 호출하고 여기에 MSDN 설명서를 읽지 않고 도움을 청합니다. 귀하의 대답은 문서에 있습니다. –
@Crowcoder 이것은 속성의 이름이 주어진 문자열을 속성의 값으로 선택하려고하는 또 다른 것입니다. –