2013-05-29 4 views
1
var emp = (from a in AdventureWorks.PersonPhones 
           join b in AdventureWorks.People 
           on a.BusinessEntityID equals b.BusinessEntityID 
           join c in AdventureWorks.PhoneNumberTypes 
           on a.PhoneNumberTypeID equals c.PhoneNumberTypeID 
           select new { a, b, c }).OrderBy(n => n.c.Name); 

익명 형식 클래스에서 값을 선택하는 linq 쿼리가 있습니다. 그냥이 쿼리를 somemethod()에 전달하고 해당 메서드의 "emp"에 저장된이 쿼리에서 toList()를 호출하려고합니다. 감사합니다.linq 선택 쿼리를 메서드에 전달합니다.

+0

http://stackoverflow.com/questions/55101/how-can-i-pass-에 원하는 속성을 선택하는 것입니다 anonymous-type-to-a-method http://stackoverflow.com/questions/6624811/how-to-pass-anonymous-types-as-parameters – dugas

+0

이 타입을'IEnumerable '로 표현할 수 있습니다. 메서드에 대한 매개 변수 유형으로 할 수 있는지 확실하지 않지만? 더 나은 방법은'{a, b, c}'에 대한 클래스 유형을 만든 다음 'IEnumerable '으로 전달하는 것입니다. – Porkbutts

답변

1

강하게 입력 된 방식으로 익명 형식을 전달할 수 없습니다 (개체로만 가능). 익명 형식 구조를 나타내는 형식을 만들거나 개체 형식에 대한 리플렉션을 사용하거나이 메서드에서 ToList() 등을 사용해야합니다.

0

당신은 IQueryable<dynamic>

public void SomeQueryMethod(IQueryable<dynamic> query) 
{ 
     var result = query.First(); 

     var a = result.a; //dynamic resolution 
} 
.... 
SomeQueryMethod(emp); //this should work 

로 전달할 수 그러나 방법에서 결과 개체의 모든 속성 액세스는 컴파일 시간을 확인하지 않고, "동적"입니다.

1

익명 형식이든 상관하지 않는 방식으로이 작업을 수행 할 수 있습니다. 관련 속성을 선택하는 방법을 전달하면 해당 작업을 수행 할 수도 있습니다.

private static void Process<T>(IEnumerable<T> data, Func<T, string> selector) { 
    foreach (var item in data) { 
     Console.WriteLine(selector(item)); 
    } 
} 

var items = from i in db.table 
      select new { property = i.originalProperty, ignored = i.ignored }; 
Process(items, (item => item.property)); 

이에 대한 대안은 단지 새로운 목록

var items = from i in db.table 
      select new { prop1 = i.prop1, prop2 = i.prop2 }; 
// ... cut ... do something that requires everything in items ... 
IEnumerable<string> justFirstProperties = items.Select(i => i.prop1); 
Process(justFirstProperties); 
+0

FYI : http://stackoverflow.com/questions/6624811/how-to-pass-anonymous-types-as-parameters – Shog9

관련 문제