2

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.

1
  • 3
    SelectMany generates an IEnumerable<> from each element in the source sequence, then concatenates all of those sequences into a single sequence. (For example, if you have a sequence of client representatives, and you want to get a sequence of all clients served by those representatives, SelectMany would do the job.) That doesn't seem to be your goal here. Assuming you're trying to filter your list for those whose CollectionId matches id, Joe Tuskan's answer is correct. Commented Mar 5, 2012 at 16:39

3 Answers 3

8

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"

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

0

You probably want to use Where

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.