C#显示嵌套列表的元素 [英] C# Displaying Elements of a Nested List
问题描述
大家好,我有一个嵌套列表,2D-List,包含Datagridview标题名称(实际上是属性名称)这就是我填写列表的方式:
Hello all, I have a nested list, 2D-List, containing "Datagridview" header names (actually attribute names) This is how I fill the lists:
List<List<string>> DscAtt = new List<List<string>>();
for (int i = 1; i < RowCount; i++)
{
for (int j = 0; j < i; j++)
{
List<string> Sublist = new List<string>();
for (int k = 1; k < ColCount - 1; k++)
{
if (ResultDGV.Rows[i].Cells[k].Value.ToString() != ResultDGV.Rows[j].Cells[k].Value.ToString())
Sublist.Add(ResultDGV.Columns[k].HeaderText);
}
DscAtt.Add(Sublist);
}
}
现在,我要做的是显示(控制台或富文本框没有真的很重要)每个子列表的第一,第二,第三和第n个元素逐行。
例如:
((a,b,c),(a,b),(c),(d,a,c),(a,b )...)
第一项:(a,a,c,d,a,...)
第二项:(b,b,a,b ,...)
第3项:(c,c,...)
....
Now, what I want to do is display (console or a rich text box doesn't really matter) first, second, thirth and nth element of each sublist line by line.
For example:
((a,b,c),(a,b),(c),(d,a,c),(a,b)...)
1st items: (a,a,c,d,a,...)
2nd items: (b,b,a,b,...)
3rd items: (c,c,...)
....
推荐答案
此代码:List< list> DscAtt = new List< list>();永远不会编译。我假设((a,b,c),(d,e),(f),(g,h,i,j),(k,l)......)是原始数据的一个例子。并且,我将假设您知道如何使用String.Split或RegEx或其他任何方法将其解析为强类型列表的集合。如果您需要帮助将嵌套列表的字符串表示解析为强类型嵌套列表或嵌套列表组,请询问。
使用此作为示例字符串列表的通用列表:
This code: List<list> DscAtt = new List<list>(); will never compile. I assume "((a,b,c),(d,e),(f),(g,h,i,j),(k,l)...)" is an example of your raw data. And, I am going to assume you know how to use either String.Split or RegEx, or whatever, to parse that into a collection of strongly typed lists. If you need help with parsing the string representation of a nested list to a strongly typed nested list, or group of nested lists, ask.
Using this as an example of a generic List of Lists of strings:
List<List<string>> testNestedList = new List<List<string>>
{
new List<string>{"a", "b", "c", "d"},
new List<string>{"e", "f", "g", "h"},
new List<string>{"i", "j", "k"},
new List<string>{"l", "m"},
new List<string>{"1", "2", "3", "4", "5"}
};
编写方法/函数以返回每个子列表中的任何特定索引值很简单:
Writing a method/function to return any particular indexed value in every sub-list is easy:
private List<string> SelectSubItems(int ndx, List<List<string>> theList)
{
List<string> matches = new List<string>();
foreach(var subList in theList)
{
if (ndx < subList.Count) matches.Add(subList[ndx]);
}
return matches;
}
注意此方法将返回List< string> ;;您可以像这样测试:
Note this method will return a List<string>; you can test it like this:
var test = SelectSubItems(4, testNestedList);
bool found = true;
for (int i = 0; found; ++i)
{
found = false;
foreach ( List <string> l in DscAtt)
{
if (l.Count > i)
{
Console.Write("{0} ", l[i]);
found = true;
}
}
Console.WriteLine();
}
这篇关于C#显示嵌套列表的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!