2
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()。谢谢!

4

3 回答 3

3

It's possible to do this in a way that doesn't care if it's a anonymous type or not - and if you pass a method for picking out the relevant property you can even do some work on it.

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));

An alternative to this would be to just select the property you want into a new list

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);
于 2013-11-19T15:39:22.097 回答
1

您不能以强类型的方式传递匿名类型(仅作为对象)。您必须创建一个类型来表示匿名类型结构,对对象类型使用反射,或者在此方法中执行 ToList() 等工作。

于 2013-05-29T20:59:49.730 回答
0

你可以把它作为IQueryable<dynamic>

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

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

但在该方法中,对结果对象的所有属性访问都是“动态的”,无需编译时检查。

于 2013-05-29T21:50:04.223 回答