Click here to Skip to main content
15,910,797 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

How can I keep multiple values in a single variable when it loop for 3 times and return all value?

ex:

grocery(egg,apple,nut);
grocery(wine,rice,bread);
grocery(bread,egg,flour);

return grocery;--> return all 3 value.
Posted
Updated 24-Aug-10 22:51pm
v2
Comments
Dalek Dave 25-Aug-10 4:51am    
Minor Edit for Grammar.
Christian Graus 25-Aug-10 5:07am    
This is obviously homework, and the extra questions you're asking below make me think you're a bit confused and really need to talk to your teacher.

Use the following code for creating a generic string list and add item in it:

System.Collections.Generic.List<string> itemList = new System.Collections.Generic.List<string>();
itemList.Add("egg");
itemList.Add("apple");
itemList.Add("nut");



Now at the time of iterating the list use foreach statement like

C#
foreach (string item in itemList)
        {
            Console.WriteLine(item);
        }


Simple...isn't it? :)
 
Share this answer
 
Write a class derived from Collection class. Override ToString() to loop and return all the items in the class. Like the example below:

C#
using System;
using System.Collections.ObjectModel;
using System.Text;
public class Groceries : Collection<string>
{
    public Groceries()
    {
    }
    public override string ToString()
    {
        StringBuilder result = new StringBuilder();
        foreach (string item in this.Items)
        {
            if (result.Length > 0)
            {
                result.Append(", ");
            }
            result.Append(item);
        }
        return result.ToString();
    }
}
 
Share this answer
 
v2
Comments
senguptaamlan 25-Aug-10 4:04am    
can you provide a sample code to achieve this???
Venkatesh Mookkan 25-Aug-10 4:49am    
I have updated my answer. Please check it out. Vote my answer, if it is helpful.
Dalek Dave 25-Aug-10 4:52am    
Very Concise Answer!
senguptaamlan 25-Aug-10 4:55am    
if the item contains a "," then what will happen ??? something like
objGrocerries.Add("egg","apple","abc,xyz");
Venkatesh Mookkan 25-Aug-10 4:55am    
Thank you.
Return array, return list, return struct... Where is the problem?
 
Share this answer
 
Comments
MissNano 25-Aug-10 2:04am    
i want to add 3 value in the list all in string. can List contain 3 value such as list.add<egg,apple,nut>. is it possible?
Christian Graus 25-Aug-10 5:07am    
You have to define a class or struct to contain your three values, not store them in a string.
now you should write here



string s;
//under the loop
s=","+s;
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900