Jmocke
Jmocke

Reputation: 271

Return List<object> from IEnumerable C#

I have a method:

public List<AxeResult> LoadAxes(string kilometriczone, string axe)
{
    IEnumerable<AxeResult> allAxes = PullAxes();
    var findAxes = allAxes.Select(a => a.KilometricZone.StartsWith(kilometriczone) || a.KilometricZone.StartsWith(axe));

    return findAxes.Cast<AxeResult>().ToList();
}

I have this error:

IEnumerable<bool> does not contain a definition for ToList and the best extension method overload Enumerable.ToList<AxeResult> ( IEnumerable<AxeResult>) requires a receptor type IEnumerable<AxeResult>

I want to return a List of AxeResult after the search operation.

Upvotes: 3

Views: 2852

Answers (2)

Tanya Petkova
Tanya Petkova

Reputation: 155

Some explanation in addition to the given answers:

Where() method acts like a filter and returns a subset of the same set

Select() method makes projection and returns new set

There is comprehensive explanation about the diffrence between .Select() and Where() methods here.

Upvotes: 2

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

What you want is to filter the collection. That's what Enumerable.Where is for:

public List<AxeResult> LoadAxes(string kilometriczone, string axe)
{
    return PullAxes()
        .Where(a => a.KilometricZone.StartsWith(kilometriczone) || 
                    a.KilometricZone.StartsWith(axe))
        .ToList();
}

Upvotes: 7

Related Questions