Rod
Rod

Reputation: 15475

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

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.

Upvotes: 0

Views: 256

Answers (4)

Juan Ayala
Juan Ayala

Reputation: 3528

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);

Upvotes: 1

mservidio
mservidio

Reputation: 13057

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[])

Upvotes: 1

AHM
AHM

Reputation: 5225

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.

Upvotes: 1

ckittel
ckittel

Reputation: 6646

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.

Upvotes: 1

Related Questions