conditional for each linq
I have a List<string>
myList like shown below:
widget1
widget2
widget3
widget4
I'd like to show this on my web page like the following
widget1 | widget3 | widget4
开发者_JS百科Let's just say if the string is "widget2" leave it out.
is there a way to do this with a linq statement?
<div>
<% myList.ForEach(x => Response.Write(Html.ActionLink(x.Name,"ActionMethod"))); %>
</div>
i know i'm asking too much but i thought i'd try.
You could do something like this:
<%= String.Join(" | ", myList
.Where(x => x.Name != "Widget 2")
.Select(x => Html.ActionLink(x,"ActionMethod").ToString()) %>
Then just modify the where statement to fit your needs. I guess it is a matter of preference, but I dislike to use Response.Write in views, and I try to avoid the ForEach() method because it doesn't work on plain IEnumerables.
Would something like this work for you?
<div>
<% myList.Where(x => x.Name != "widget2").ToList().ForEach(x => Response.Write(Html.ActionLink(x.Name,"ActionMethod"))); %>
</div>
Introducing the "conditional" part before the ForEach(...)
call.
You could use the String.Join method in combination with Linq:
List<string> list = new List<string>();
// populate list here.
string result = String.Join(" | ", list.Where(c => c.Name != "widget2").ToList());
String.Join Method (String, String[])
var list = new List<string>() { "one", "two" };
var agg = list.Aggregate(new StringBuilder(),
(sb, item) => sb.AppendFormat((item == list.First()) ? "{0} " : "| {0}", item));
or if you don't want to do the first check every time
var agg = list.Aggregate(new StringBuilder(),
(sb, item) => sb.AppendFormat("{0} | ", item));
if (agg.Length > 0)
agg.Remove(agg.Length - 2, 2);
精彩评论