gpt4 book ai didi

c# - 循环遍历集合

转载 作者:行者123 更新时间:2023-11-30 14:19:30 25 4
gpt4 key购买 nike

我有两个类(class)

class A
{
public string something { get; set; }
public IList<B> b= new List<B>();
}

class B
{
public string else { get; set; }
public string elseelse { get; set; }
}

我填充了一个名为 obj 的 A 类对象。我怎样才能遍历这个对象并打印值。我是否必须像这里的一个节目那样使用两个 foreach,还是有更好的方法?

 foreach (var z  in obj)
{
// print z.something;
foreach (var x in z.b)
{
// print x.elseelse;
}
}

最佳答案

var qry = from z in obj
from x in z.b
select new { z, x };
foreach (var pair in qry)
{
Console.WriteLine("{0}, {1}", pair.z.something, pair.x.elseelse);
}

var qry = from z in obj
from x in z.b
select new { z.zomething, x.elseelse };
foreach (var item in qry)
{
Console.WriteLine("{0}, {1}", item.something, item.elseelse);
}

或转换字符串:

var qry = from z in obj
from x in z.b
select z.zomething + ", " + x.elseelse;
foreach (string s in qry)
{
Console.WriteLine(s);
}

关于c# - 循环遍历集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2578213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com