How to use the LINQ where expression?

I'm implementing the service \ repository pattern in a new project. I've got a base interface that looks like this. Everything works great until I need to use the GetMany method. I'm just not sure how to pass a LINQ expression into the GetMany method. For example how would I simply sort a list of objects of type name?

nameRepository.GetMany( ? )

public interface IRepository<T> where T : class
{
    void Add(T entity);
    void Update(T entity);
    void Delete(T entity);
    void Delete(Expression<Func<T, bool>> where);
    T GetById(long Id);
    T GetById(string Id);
    T Get(Expression<Func<T, bool>> where);
    IEnumerable<T> GetAll();
    IEnumerable<T> GetMany(Expression<Func<T, bool>> where);

}



 public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where)
 {
    return dbset.Where(where).ToList();
 }

Answers


Assuming that you had an implementation of IRepository<MyClass>, you would make a call to GetMany like so:

IRepository<MyClass> repository = ...;

IEnumerable<MyClass> filtered = repository.GetMany(
    mc => true);

Note the mc => true lambda expression. mc in this case is the parameter (in this case, of type MyClass) passed to the Expression<Func<T, bool>> which will be evaluated (one would assume through an IQueryable<T>) and the mc.SomeProperty == someValue is an expression which returns true, which is the second type parameter of the Expression<Func<T, bool>>.

Once you have the filtered, you can use the order by clause (or the OrderBy extension method, they're the same) to sort the results, like so:

var filteredAndOrdered = filtered.OrderBy(mc => mc.MyProperty);

Note that GetMany returns an IEnumerable<T>, not an IQueryable<T>; this is important if your result set is large, as the ordering will happen on the client, and not be sent to the server.

For an OrderBy operation, this can be expensive because it has to go through the entire sequence (to order) before returning the first result.


Need Your Help

Submenu disappears when I am over video with mouse but still hovering submenu

html css

So I am having this problem and I can figure out how to do it when on other pages it works fine but with video don't. I would be grateful for any advice. It quite long but I hope understandable. I ve

how to use both solid brush and imagebrush in listview.background

wpf user-controls wpf-controls brush

The problem i have is how to use both the solid brush and imagebrush tags in listview.bakcground? I have set an image as background in listview but i m not able to set any color to the background?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.