Reputation: 1033
Im new to linq and trying to learn some basic? functionality. I have a string that im splitting into a string array and I want to query the array for values. My code.
string input = "a1,b2,c3,d4";
var collection = input.Split(',');
string output = collection.OfType<string>().Where(r => (string)r.Contains("a").FirstOrDefaule();
I think im on the right track but Its not quite there. I want the output to be a1.
The error is cannot convert bool to string, which makes sense, but how would you do this without using the contains method?
Upvotes: 0
Views: 1234
Reputation: 354
Try this one
string output= collection.Where(r => r.Contains("a")).FirstOrDefault();
Upvotes: 0
Reputation: 682
Why you use cast to string in Where clause? You don't need it. Try this
string output= urls.OfType<string>().Where(r => r.Contains("a")).FirstOrDefault();
Upvotes: 0
Reputation: 5093
This code should work:
string output = collection.First(r => r.Contains("a"));
Contains
is probably the most efficient way.
Where
gives you a new list of all elements which have an "a"; First
(or FirstOrDefault
) will return a single value.
Upvotes: 5