简体   繁体   中英

how to convert from IEnumerable<type> to type?

I am using EF 4 with repository pattern which has the generic query method shown below:

public IEnumerable<T> Query(Expression<Func<T, bool>> filter) 
    { 
        return objectSet.Where(filter); 
    } 

I know I can select a complete object like this:

context.PeriodRepository.Query(a => a.EntityId == selectedEntityId); 

But I want to pass a Linq query that returns it as type instead of IEnumerable<type> using a LINQ expression without changing the method. Please advise me how to do that.

使用First()FirstOrDefault()方法并传递谓词以查找所需的元素(如果不是第一个元素)。

A Query describes the operations performed on the list; you must perform the query to get the result(s).

Using .ToList() / .ToArray() will return all items that match the query. Use .First() to get the first item that matches or .FirstOrDefault() to get the first item or the default value for no matches.

The default value for a class is null .

I think your code should be like this:

var myMatch = context.PeriodRepository
   .Query(a => a.EntityId == selectedEntityId)
   .First();

Also note that, First() will throw an exception when there is no match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM