c# - 时间: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);
感谢您的帮助
解决方案
第一:
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))))
推荐阅读
- xcode - 不要缩进 Xcode 风格的注释掉的代码
- python - 创建演示文稿时如何在 Google Slides API 中应用自定义布局
- python - DataFrameGroupBy 对象到 DataFrame
- javascript - Chrome 扩展程序不会在新标签页上自动激活
- javascript - 在元素样式上设置 .cssText 时转换不起作用?
- c# - 如何在运行时编辑 app.xaml 文件?
- php - PHP AES-128-CBC 使用十六进制密钥进行编码
- c - 数组的前 2 个元素在 for 循环后不显示在输出中
- c# - 在将类保存到 xml 文件之前加密属性
- django - 在Django中的整个表(所有字段,所有列,所有行)中查找一个字符串