Dharma Teja
Dharma Teja

Reputation: 45

cannot implicitly convert type system.collections.generic.IEnumerable<string> to string[]

Trying to solve and getting to following error

public String[] Any()
{                            
    var lastSixMonths = Enumerable.Range(0, 6).Select(i => DateTime.Now.AddMonths(i - 6)).Select(date => date.ToString("MM/yyyy"));

    return lastSixMonths;
}

Upvotes: 3

Views: 14571

Answers (5)

dead_webdev
dead_webdev

Reputation: 256

public String[] Any()
{   
    return Enumerable.Range(0, 6).Select(i => DateTime.Now.AddMonths(i - 6)).Select(date => date.ToString("MM/yyyy")).ToArray();
}

What needs to be understood

Understand the requirement, fetching 6 months of data from the database using LINQ will provide us a collection of data or multiple rows. So if we want we can limit it by giving condition and using .FirstorDefault or if we need an array or in the list format we can use .ToList or .ToArray.

Upvotes: 0

Johnny
Johnny

Reputation: 9519

Since the lastSixMonths is the IEnumerable<string> and you are expecting an array, try this:

return lastSixMonths.ToArray();

I have also created .NET Fiddle to show how you could print the string[].

Upvotes: 5

Cleptus
Cleptus

Reputation: 3541

Your problem: Your .Select() call does return an IEnumerable that you have to explicit convert into an array.

An improvement: There was no need to make two .Select() calls one after the other, you could have made with just one call.

public String[] Any()
{                            
    IEnumerable<string> lastSixMonths = Enumerable.Range(0, 6).Select(i => DateTime.Now.AddMonths(i - 6).ToString("MM/yyyy"));
    // Now we convert it into an array.
    string[] returned = lastSixMonths.ToArray();
    return returned;
}

Upvotes: 1

Bart van der Drift
Bart van der Drift

Reputation: 1336

This should do it:

public String[] Any()
{                            
    IEnumerable<String> lastSixMonths = Enumerable.Range(0, 6).Select(i => DateTime.Now.AddMonths(i - 6)).Select(date => date.ToString("MM/yyyy"));
    return lastSixMonths.ToArray();
}

Upvotes: 0

Marco Salerno
Marco Salerno

Reputation: 5203

This way:

public String[] Any()
{   
    return Enumerable.Range(0, 6).Select(i => DateTime.Now.AddMonths(i - 6)).Select(date => date.ToString("MM/yyyy")).ToArray();
}

Why didn't it work?

Linq's Select returns an IEnumerable with filtering, sorting etc, instructions.

It's up to you, to decide what to retrieve, if a single element FirstOrDefault or more than one element like ToList , ToArray , ToDictionary etc..

Upvotes: 1

Related Questions