Reputation: 541
Sorry if this has been answered - I have read at least 20 questions that answer an almost identical question but they're all with slightly different circumstances or I can't get them to work.
That's also despite the fact what I want is far more simple! :(
All I want to do is return all the elements of a string array that start with "ABC".
So {"ABC_1", "ABC_2", "ABC_3", "123_1", "ABC_4"}
Will return {"ABC_1", "ABC_2", "ABC_3", "ABC_4"}
Using Linq with Lambda Expressions:
So the logic would be similar to the following:
FilteredArray = StringArray.Where(String.StartsWith("ABC"));
Everytime I try something similar to the above it returns no values.
Thank you in advanced for your help and apologies in advanced for not being able to solve this independently.
P.S If you know of a link that would provide me with a good tutorial on Linq with Lambda Expressions that would be greatly appreciated.
Upvotes: 1
Views: 375
Reputation: 40990
You need to use the correct syntax in your lambda expression like this
var FilteredArray = StringArray.Where(x => x.StartsWith("ABC")).ToArray();
If you want to learn about Linq expressions then here is a very good solution available for you 101 Linq Samples
Upvotes: 2
Reputation: 4319
I'm not actually sure the original example would compile? Your missing the lambda syntax. This will work correctly. Basically you need to specify the input parameter for the where clause (each of the strings in the array) this is x. Then you do you're string startswith check on that.
var filtered = StringArray.Where(x => x.StartsWith("ABC"));
Upvotes: 2
Reputation: 727137
If you want to make an array from an array, you need to use ToArray
. You also need to get your LINQ syntax right:
// This assumes that FilteredArray is declared as String[]
FilteredArray = StringArray.Where(str => str.StartsWith("ABC")).ToArray();
Note that Where
is not all-caps because identifiers in C# are case-sensitive. Also note the use of the lambda syntax inside the Where
method.
Upvotes: 4