2010-08-15 2 views
1

어떻게 두 번째 유형에 코드 아래 변경할 수 있습니다 : 내가 먼저 => 두 번째 구문처럼 아주 유연 코드를 사용하려고 ...linq에서 Func <Tkey,T>을 어떻게 사용할 수 있습니까?

첫 번째 유형에게 내가 필요



    private void Form1_Load(object sender, EventArgs e) 
     { 
      List<City> cities = new List<City> 

      { 
       new City{ Name = "Sydney", Country = "Australia" }, 
       new City{ Name = "New York", Country = "USA" }, 
       new City{ Name = "Paris", Country = "France" }, 
       new City{ Name = "Milan", Country = "Spain" }, 
       new City{ Name = "Melbourne", Country = "Australia" }, 
       new City{ Name = "Auckland", Country = "New Zealand" }, 
       new City{ Name = "Tokyo", Country = "Japan" }, 
       new City{ Name = "New Delhi", Country = "India" }, 
       new City{ Name = "Hobart", Country = "Australia" } 
      }; 
      List<string> mylistName = GetData(cities, c => c.Name); 
      foreach (string item in mylistName) 
      { 
       listBox1.Items.Add(item); 
      } 
      List<string> mylistCountry = GetData(cities, c => c.Country); 
      foreach (string item in mylistCountry) 
      { 
       listBox2.Items.Add(item); 
      } 
     } 

     public List<T> GetData<T>(List<City> cities, Func<City, T> selector) 
     { 
      return cities.Select(selector).ToList(); 
     } 

    } 
    public class City 
    { 

     public string Name { get; set; } 
     public string Country { get; set; } 

    } 

두 번째 유형 아래 :



     public List<T> GetData<T>(List<Tkey> cities, Func<Tkey, T> selector) 
     { 
      return cities.Select(selector).ToList(); 
     } 

답변

7

당신은 무엇 TKey 선언하지 않은 - 당신은 네브라스카

public List<T> GetData<TKey, T>(List<TKey> cities, Func<TKey, T> selector) 
{ 
    return cities.Select(selector).ToList(); 
} 

그러나, 나는 강력하게 하나 개 이상의 형식 매개 변수가있는 경우, 당신은 그들에게 모든 "전체"이름을 지정하는 것이 좋습니다 것입니다 : 에드 방법에 대한 또 다른 제네릭 형식 매개 변수가 있는지 확인합니다. 예를 들어, 내가 사용하십시오 :

public List<TResult> GetData<TSource, TResult>(List<TSource> cities, 
               Func<TSource, TResult> selector) 
{ 
    return cities.Select(selector).ToList(); 
} 

마음 당신, 정말 간단합니다 경우 개인적으로가 아니라 단지 자신을 Select()ToList()를 호출 할 것입니다. 추가 메서드는 많이 절약되지 않으며 표준 LINQ 메서드보다 대부분의 개발자에게 친숙하지 않습니다.

+0

explane 할 수 있겠습니까? 정말 간단하다면 개인적으로 Select() 및 ToList()를 직접 호출하는 편이 낫습니다. 추가 메서드는 많이 저장하지 않으며 대부분의 개발자에게 친숙하지 않습니다. 표준 LINQ 방법. " – Penguen

+1

@Phsika :'GetSource' 메소드는'Select '를 직접 호출하는 것보다 훨씬 많은 돈을 벌 수 있습니다. –

+0

Jon Skeet 솔루션 위에 원하는 코드를 알려주시겠습니까? – Penguen

관련 문제