Kennyist
Kennyist

Reputation: 63

c# finding items from a list with linq to an array

Just wondering how would I get something like this to work?

void EditListUpdate(int id)
    {
        string[] editListMod = modules.Where(x => x.Id == id).ToArray();
    }

Modules is a list.

Upvotes: 0

Views: 189

Answers (3)

Wasafa1
Wasafa1

Reputation: 805

the problem is the type returned by the method.

You can use explicitly by declaring

 Module[] editListMod = modules.Where(x => x.Id == id).ToArray();

or use the super nice c#'s type inference by magic word:

 var editListMod = modules.Where(x => x.Id == id).ToArray();

Upvotes: 2

Tim
Tim

Reputation: 28530

Assuming what you posted is your actual code, you're missing the parentheses on ToArray. ToArray() is a method call.

string[] editListMod = modules.Where(x => x.Id == id).ToArray();

That should resolve the error you saw (Cannot convert method group 'ToArray' to non-delegate type 'string[]'. Did you intend to invoke the method?)

Updated

You're new error: Cannot implicitly convert type 'stageManagement.Module[]' to string[]'

You need to change the type of editListMod from string[] to stageManagement.Module[]. Your LINQ statement will select all stageManagement.Module objects that have the matching ID.

In other words:

Module[] editListMod = modules.Where(x => x.Id == id).ToArray();

Upvotes: 1

K Mehta
K Mehta

Reputation: 10533

modules is of type Module in your code. Your editListMod is of type string[], so the compiler is telling you that it cannot implicitly convert that to type Module[]. To fix this, try:

Module[] editListMod = modules.Where(x => x.Id == id).ToArray();

Upvotes: 1

Related Questions