Ola
Ola

Reputation: 1208

why is this linq query return a boolean and not the first result of the select?

I have a string array with 5 items. How to get one of these 5 items by a linq query?

Code below returns only a boolean true.

string[] allWebTemplateSettings =SiteLidmaatschapSettings.Current.ProvisioningSettings;
var webTemplate = allWebTemplateSettings
           .Select(x => x.StartsWith(string.Format("Template:{0}", web.WebTemplate)))
           .FirstOrDefault();

Upvotes: 14

Views: 7976

Answers (4)

user1726343
user1726343

Reputation:

Well, you're getting an IEnumerable of bools with your Select, then you pick the first one if there are any. That's why you're getting a bool as your answer.

I think what you actually want is this:

string[] allWebTemplateSettings = SiteLidmaatschapSettings.Current.ProvisioningSettings;
var prefix = string.Format("Template:{0}", web.WebTemplate);
var webTemplate = allWebTemplateSettings
    .FirstOrDefault(x => x.StartsWith(prefix));

I've moved the string formatting operation out of the predicate since it is wasteful to recompute it for each element in your collection (especially if the collection is long).

Upvotes: 5

Ham3d
Ham3d

Reputation: 340

Use Where instead of Select:

var webTemplate = allWebTemplateSettings.Where(x => x.StartsWith(string.Format("Template:{0}", web.WebTemplate))).FirstOrDefault();

Upvotes: 12

Rawling
Rawling

Reputation: 50144

You are confusing Select, which selects a new value based on each existing value of a sequence, with Where, which filters a sequence so it only contains items where a condition is met.

The simplest change is to replace your usage of Select with Where.

string[] allWebTemplateSettings = SiteLidmaatschapSettings.Current.ProvisioningSettings;
var webTemplate = allWebTemplateSettings
    .Where(x => x.StartsWith(string.Format("Template:{0}", web.WebTemplate)))
    .FirstOrDefault();

The other answers have rolled this usage of Where into FirstOrDefault without explaining your underlying confusion.

Upvotes: 2

Mathew Thompson
Mathew Thompson

Reputation: 56439

That's because StartsWith returns a bool and you're saying Select that bool based on whether it starts with that value or not. So actually, you're not even filtering on that value at all because you're not using a filter expression.

Actually, you only need FirstOrDefault as the list is already a List<string>

string[] allWebTemplateSettings = SiteLidmaatschapSettings.Current.ProvisioningSettings;
 var webTemplate = allWebTemplateSettings
    .FirstOrDefault(x => x.StartsWith(string.Format("Template:{0}", web.WebTemplate)));

Upvotes: 0

Related Questions