简体   繁体   中英

Check if array contains string in aggregate function in C#

My code:

allScripts += externalJs.Aggregate(allScripts, (current, js) 
            => current + String.Format("<script src=\"{0}\"></script>", js.Url));

I'd like to check if the parameter Url contains the string "jquery".

allScripts += externalJs.Aggregate(allScripts, (current, js) =>js.Url.Contains("jquery") ? current + String.Format("<script src=\"{0}\"></script>", js.Url) : current);

EDIT: Per the comment below, a better answer would be to pre-filter the list:

allScripts += externalJs.Where(js => js.Url.Contains("jquery")).Aggregate(allScripts, (current, js) => current + String.Format("<script src=\"{0}\"></script>", js.Url);

A quick warning with this solution -- it solves the problem as posted, but you're adding the result to "allScripts" but also including it as the seed to the Aggregate, so you'll probably duplicate your original "allScripts" in this case. Solutions are to not provide a seed, or to only use an "=" instead of "+=" on the assignment.

tnx a lot! that worked perfectly, check the last parenthesis.

allScripts += externalJs.Where(js => !js.Url.Contains("jquery-ui")).Aggregate(allScripts, (current, js) => current + String.Format("<script src=\"{0}\"></script>", js.Url));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM