首页 > 解决方案 > 时间:2019-05-10 标签:c#return loop without using foreach

问题描述

您好,我
在 test.cs 中的代码中需要一些帮助:

public class test
    {
        public string[] content ={
                    "Username:Peter",
                    "ID:1",
                    "Username:Nike",
                    "ID:2"};
        public IEnumerable<string> Name
        {
            get
            {
                var username = content.Where(a => a.StartsWith("Username:")).ToList();
                for(int i = 0; i < username.Count(); i++)
                {
                    yield return username[i].Substring(username[i].IndexOf(":") +1); // Displays the usernames (Peter, Nike)
                }
            }
        }
        public IEnumerable<string> ID
        {
            get
            {
                var username = content.Where(a => a.StartsWith("ID:")).ToList();
                for (int i = 0; i < username.Count(); i++)
                {
                    yield return username[i].Substring(username[i].IndexOf(":") +1); // Displays the ID (1, 2)
                }
            }
        }
    }

主文件中的代码:

var test = new test();
foreach (var l in test.Name)
    treeView1.Nodes.Add(l);

一切正常,它显示正确的名称,但我不想使用 foreach 我想添加它:

treeView1.Nodes.Add("Name: " + test.Name + " ID:" + test.ID);

感谢您的帮助

标签: c#

解决方案


第一:

public class test
{
    public string[] content ={
        "Username:Peter",
        "ID:1",
        "Username:Nike",
        "ID:2"};

    public Dictionary<string, string> contents;

    public Dictionary<string, string> Contents
    {
        get
        {
            if (contents == null)
            {
                InitContents();
            }

            return contents;
        }
    }

    private void InitContents()
    {
        contents = new Dictionary<string, string>();

        for (var i = 0; i < content.Length; i++)
        {
            contents.Add(GetValue(content[i]), GetValue(content[i + 1]));
            i++;
        }
    }

    private string GetValue(string data)
    {
        return data.Substring(data.IndexOf(":", StringComparison.Ordinal) + 1);
    }

    public IEnumerable<string> GetContents()
    {
        return Contents.Select(x => "Name: " + x.Key + " ID:" + x.Value);
    }


}

然后使用:

treeView1.Nodes.AddRange(yourTests.Contents.Select(x=>new TreeNode("Name:"+x.Key+"Id:"+x.Value))))

推荐阅读