开发者

Parse a list to a string

Maybe I'm being too clever, but I have a method that goes through a enumerable List(Collections) and returns it as an ........... enumerable List(Sparkles).

I wanted to enclose the first 开发者_如何学Golist(Collections) in a class that handles validation and various other duties, otherwise I'd handle directly with the Collections.

I'm pretty sure that sounds more difficult that I should of made it. So the class returns a list(Sparkles) through a method called getSparkles().

I thought I was do a foreach right:

string msg;
List<string> layoutListNames = new List<string>();

foreach (string name in layoutList.getLayout());
{
     msg = "\n" + name;
}

The compiler, however, disagrees with me.

Give me a hint. I would like to learn.

Edit: Sorry. getLayout() returns a List<>. And I removed the semicolon. Oh /facepalm.

I wrote this in a constructor to test a class and forgot to change the name of the constructor to match the class name. Thanks for the incredibly fast responses.


Whats wrong is the ';' behind foreach (string name in layoutList.getLayout()) ;

Remove that, and the compiler agrees..

Suggestion for making it better:

string msg = string.Join("\n", layoutListNames);


For one thing: You need to remove the ; after the foreach. Otherwise this will be an empty loop statement and in the following block name will not be declared.


and try it again...

    static void Main(string[] args)
    {
        string msg = null;
        List<string> layoutListNames = new List<string>() { "test1","test2"};

        foreach (string name in layoutListNames)
        {
            if (msg != null) msg += "\n";
            msg += name;
        }

        Console.WriteLine("at 1:" + msg);

        msg = string.Join("\n", layoutListNames.ToArray());

        Console.WriteLine("at 2:" + msg);

        Console.Read();
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜