Sign in to follow this  
nooblet

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

Recommended Posts

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! :)

Share this post


Link to post
Share on other sites
Its not a neat solution, for the first item just write it, then for subsequent items write a comma then write the item. Maybe:

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

Share this post


Link to post
Share on other sites
[quote name='Nanoha' timestamp='1318114016' post='4870627']
Its not a neat solution, for the first item just write it, then for subsequent items write a comma then write the item. Maybe:

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

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 [url="http://msmvps.com/blogs/jon%5Fskeet/archive/2007/07/27/smart-enumerations.aspx"]here[/url] if looking for a general purpose way of doing the above. However, for the specific OP, String.Join might be the most simple.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this