Reputation: 2533
I have a List<string>
and I want to identify either the first or last element in the list so I can identify a different function to do with that item.
Eg.
foreach (string s in List)
{
if (List.CurrentItem == (List.Count - 1))
{
string newString += s;
}
else
{
newString += s + ", ";
}
}
How would I go about defining List.CurrentItem
? Would a for
loop be better in this situation?
Upvotes: 1
Views: 3107
Reputation: 20595
You can use a linq based solution
Example :
var list = new List<String>();
list.Add("A");
list.Add("B");
list.Add("C");
String first = list.First();
String last = list.Last();
List<String> middle_elements = list.Skip(1).Take(list.Count - 2).ToList();
Upvotes: 1
Reputation: 166606
Rather make use of String.Join
Concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member.
It is a lot simpler.
Something like
string s = string.Join(", ", new List<string>
{
"Foo",
"Bar"
});
Upvotes: 8
Reputation: 4560
you can use the counter like this
int counter = 0 ;
foreach (string s in List)
{
if (counter == 0) // this is the first element
{
string newString += s;
}
else if(counter == List.Count() - 1) // last item
{
newString += s + ", ";
}else{
// in between
}
counter++;
}
Upvotes: 0
Reputation: 2115
Try something like this:
string newString = "";
foreach (string s in List)
{
if( newString != "" )
newString += ", " + s;
else
newString += s;
}
Upvotes: 0