jamheadart
jamheadart

Reputation: 5343

c# Can I apply a method to an IQueryable to convert it to a list?

I'm trying to return a list of Obj1 types but I first need to pull these using an IQueryable LINQ statement which gives me a list of Obj2 types, and have a method that converts them to the required type which I apply by using a foreach loop

public List<Obj1> GetObj1List(int id)
{
    List<Obj2> obj2List = Select(x => x.ObjTable.Where(a => a.Id == id)).ToList();
    List<Obj1> obj1List = new List<Obj1>();

    foreach(Obj2 o in obj2List)
    {
        obj1List.Add(MapObject2ToObject1(o, OtherMethod));
    }
    return obj1List;
}

Is there any way I can wrap my Select statement to apply the MapObject2ToObject1 method to the results without having the foreach line?

Upvotes: 3

Views: 260

Answers (2)

phuzi
phuzi

Reputation: 13079

Should be quite easy.

public List<Obj1> GetObj1List(int id)
{
    var obj1List = Select(x => x.ObjTable.Where(a => a.Id == id))
        .Select(o => MapObject2ToObject1(o, OtherMethod))
        .ToList();
    return obj1List;
}

Updated with updated method signature for MapObject2ToObject1

Upvotes: 6

Jon Skeet
Jon Skeet

Reputation: 1503469

You want AsEnumerable to effectively use LINQ to Objects for the last mapping part:

public List<Obj1> GetObj1List(int id) =>
    Select(x => x.ObjTable.Where(a => a.Id == id)
    .AsEnumerable()
    .Select(MapObject2ToObject1)
    .ToList();

(I'm assuming that Select is a method in the current class that returns an IQueryable<Object2>, given your sample. I'm also assuming you're using C# 6 or higher, so you can use an expression-bodied method like this. If not, put it all in braces and add a return statement.)

Upvotes: 4

Related Questions