ediblecode
ediblecode

Reputation: 11971

Linq to Sql - SelectMany

I am trying to return a List<Image> but am having trouble with the following method:

public List<Image> GetImageByCollection(int id)
    {
        List<Image> images = collectionDb.Images.SelectMany(i => i.CollectionId == id);
        return images;
    }           

I am new to Linq so its probably something basic but hopefully you can see what I am trying to do. If I am not clear please say and I will try to clarify.

Upvotes: 2

Views: 5104

Answers (3)

Joe
Joe

Reputation: 82554

You actually what a Where and ToList

List<Image> images = collectionDb.Images
                             .Where(i => i.CollectionId == id).ToList();

Select and SelectMany will return an IEnumerable<T> of the predicate. For example,

IEnumerable<int> collectoinIds = collectionDb.Images
                                             .Select(i => i.CollectionId);

Now SelectMany will "flatten" a list of objects.

public class Test
{
    IList<string> strings { get; set; } 
}

...

List<Test> test = new List<Test> 
{ 
    new Test { strings = new[] { "1", "2" } },
    new Test { strings = new[] { "3", "4" } },
};

IEnumerable<string> allStrings = test.SelectMany(i => i.strings);

allStrings contains "1", "2", "3", "4"

Upvotes: 8

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47038

You probably want to use Where

List<Image> images = collectionDb.Images.Where(i => i.CollectionId == id).ToList();

Upvotes: 0

Matthias Meid
Matthias Meid

Reputation: 12513

I think you might rather be looking for Where and ToList:

collectionDb.Images.Where(i => i.CollectionId == id).ToList();

Upvotes: 1

Related Questions