[C#] Checking the amount of items in a List?

Started by
5 comments, last by nooblet 12 years, 6 months ago
Hey all,

I'm working on my own text-RPG. It's very basic, which is what I'm aiming at, but I kind of ran into a small issue. I have a function that display's the player's inventory list, and writes out the items to the console. Below is the function, and under that is further explanation of what I'm trying to do:

[source lang="csharp"]


// Return the list of items in the Player's inventory.
public void ItemList()
{
if (mInventory.List.Count() <= 0)
{
Console.Clear();
Console.WriteLine("{0} has no items in their inventory.", Name);
}
else
{
Console.Clear();
Console.Write("{0}'s inventory contains the following items:", Name);
}

foreach (string items in mInventory.List)
{
Console.WriteLine(" \"{0}\",", items);
}

Console.ReadLine();
}
[/source]

Now, I want to "modify" the line:

[source lang="csharp"]
Console.WriteLine(" \"{0}\",", items);
[/source]

To display a comma if there's an object after the current item. I'm a bit lost in coming up with a solution for this one. I appreciate any help or suggestions provided! :)
Advertisement
Its not a neat solution, for the first item just write it, then for subsequent items write a comma then write the item. Maybe:

bool first = true;
foreach (string items in mInventory.List)
{
if(first)
{
Console.WriteLine(" \"{0}\"", items);
first = false;
}
else
{
Console.WriteLine(", \"{0}\"", items);
}
}

Interested in Fractals? Check out my App, Fractal Scout, free on the Google Play store.

How about something like this?

[source lang="csharp"]
for (int i = 0; i < mInventory.List.Count; i++)
{
Console.Write("\"{0}\"{1}", mInventory.List, i < mInventory.List.Count -1 ? "," : string.Empty);
}
[/source]
Alternately you can use String.Join() on your list with a "," separator.

Alternately you can use String.Join() on your list with a "," separator.


Which would be way better lmfao, thanks, I never remember String.Join()!

Its not a neat solution, for the first item just write it, then for subsequent items write a comma then write the item. Maybe:

bool first = true;
foreach (string items in mInventory.List)
{
if(first)
{
Console.WriteLine(" \"{0}\"", items);
first = false;
}
else
{
Console.WriteLine(", \"{0}\"", items);
}
}



To add more solutions to the mix, Jon Skeet wrote a smart enumerable class that supports IsFirst and IsLast queries (among a couple others), which can be found here if looking for a general purpose way of doing the above. However, for the specific OP, String.Join might be the most simple.
Thank you all very much! ?

This topic is closed to new replies.

Advertisement