如何在泛型列表中遍历列表
本文关键字:列表 遍历 泛型 | 更新日期: 2023-09-27 18:24:14
我正试图在Object
的的通用列表中对每个列表集合的每个对象进行序列化
举个例子,我可以遍历通用列表temp_list
中的每个列表对象alist
,但由于在运行时之前我不知道v
对象是什么,所以我不能引用它的列表:
List<AObj> alist = new List<AObj>();
List<BObj> blist = new List<BObj>();
// .. objects initialized here, plugged into respective lists, etc.
List<Object> temp_list = new List<Object>();
temp_list.Add(alist);
temp_list.Add(blist);
foreach (var v in temp_list)
{
// Here I want to iterate through the list in each v
/*
foreach (var w in v) <-- This obviously doesn't work because the compiler
doesn't know what v is until run-time
*/
}
其中alist
和blist
只有基本对象:
class AObj
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
class BObj
{
public string Property3 { get; set; }
public string Property4 { get; set; }
}
有没有一种方法可以让我拥有一个双foreach
,它可以让我遍历泛型列表中列表中的每个对象。
由于编译器直到运行时才知道v
,所以它几乎陷入了困境。
如果您确定它是可迭代的,那么强制转换将在中工作
例如
foreach (var v in temp_list)
{
// Here I want to iterate through the list in each v
foreach (var w in v as IEnumerable) //casting to IEnumerable will let you iterate
{
//your logic
}
}
或者,您可以更改外部列表类型以避免投射
来自
List<Object> temp_list = new List<Object>();
至
List<IEnumerable> temp_list = new List<IEnumerable>();
如果这是不可能的,那么在迭代之前添加一个检查应该会使代码安全
foreach (var v in temp_list)
{
// Here I want to iterate through the list in each v
//casting to IEnumerable will let you iterate
IEnumerable list = v as IEnumerable;
//check if successful
if(list != null)
{
foreach (var w in list)
{
//your logic
}
}
else
{
//else part if needed
}
}
您需要将临时列表声明为IEnumerable<object>
列表,而不是object
列表。具体操作如下:
var alist = new List<AObj>();
var blist = new List<BObj>();
// .. objects initialized here, plugged into respective lists, etc.
var temp_list = new List<IEnumerable<object>>();
temp_list.Add(alist);
temp_list.Add(blist);
foreach (var v in temp_list)
{
foreach (var x in v)
{
}
}
使用linq。。。
List<AObj> alist = new List<AObj>();
List<BObj> blist = new List<BObj>();
// .. objects initialized here, plugged into respective lists, etc.
List<object> temp_list = new List<object>();
temp_list.Add(alist);
temp_list.Add(blist);
var allObjects = temp_list
.Select(l => l as IEnumerable<object>) // try to cast to IEnumerable<object>
.Where(l => l != null) // filter failed casts
.SelectMany(l => l); // transform the list of lists into a single sequence of objects
foreach (var o in allObjects)
{
// enumerates objects in alist and blist.
}