【发布时间】:2017-06-16 08:06:26
【问题描述】:
我知道这里有很多关于此的问题,其他地方也有大量信息。出于某种原因,我不能让它工作。这是我的起点之一...Add entire row to DataTable at once using list
这是一个列表列表。第一个列表应该是列标题。
dat 是一个 List<List<string>>,看起来像:
{"index", "filename0", "filename1"},
{"A-100", "yes", "no"},
{"A-200", "no", "yes"}
etc...
代码:
/// Dictionary containing as Key => FileName
/// as Value => All drawing numbers found in FileName
Dictionary<string, List<string>> AllDrawingLists = new Dictionary<string, List<string>>();
private void processGrid()
{
List<string> index = new List<string>();
/// Build a comprehensive INDEX from the dictionary - A list
/// of all the drawing numbers found in all the FIlenames
foreach (KeyValuePair<string, List<string>> item in AllDrawingLists)
{
foreach (string dwg in item.Value)
{
if (index.Contains(dwg) == false)
{
index.Add(dwg); }
}
}
List<List<string>> dat = new List<List<string>>();
List<String> headers = new List<string>();
headers.Add("Index");
foreach (KeyValuePair<string, List<string>> item in AllDrawingLists)
{
headers.Add(item.Key);
}
dat.Add(headers);
foreach(string i in index)
{
List<string> row = new List<string>();
row.Add(i);
foreach(KeyValuePair<string, List<string>> item in AllDrawingLists)
{
string cell = "no";
if (item.Value.Contains(i))
{
cell = "yes";
}
row.Add(cell);
}
dat.Add(row);
}
dataGrid.Columns.Clear();
DataTable dt = new DataTable();
int ii = 0;
foreach (List<string> row in dat)
{
if (ii == 0)
{
foreach(string t in row)
{
dt.Columns.Add(t);
}
ii++;
} else
{
dt.Rows.Add(row.ToArray<string>());
}
}
dataGrid.ItemsSource = dt.AsDataView();
}
我的预期结果是:
| | | |
| index | file1 | file2 |
-------------------------
| A-100 | yes | no |
-------------------------
| A-200 | no | yes |
-------------------------
| A-300 | yes | yes |
但是我得到了:
| | | |
| index | file1 | file2 |
-------------------------
| A-100 | | |
-------------------------
| A-200 | | |
-------------------------
| A-300 | | |
列表列表是我所期望的,显然它适用于列的定义。我不确定为什么在第一列之后没有任何内容进入 DataGrid
这是 dat 的输出。这就是我认为我正在寻找的东西。占所有行和列。
Index C:\py\narrver2\lists.txt C:\py\narrver2\list2.docx
A-1001 yes yes
A-1002 yes yes
A-1003 yes yes
A-1004 no yes
A-1005 no yes
A-1006 no yes
A-1007 no yes
【问题讨论】:
-
您是否正确初始化了列表列表?因为我刚刚测试了你的代码并让它对我有用。
-
谢谢。我不知道。我大约一周前开始使用 C#,但仍然掌握了窍门。我已经添加了整个班级。
-
我认为问题出在您的列表初始化列表中。我不确定
AllDrawingLists包含什么。检查它以确保它们正确。您可以通过Console.Write()尝试列表中的每个项目,例如foreach (List<string> listDat in dat) { foreach (string strDat in listDat) { Console.Write(strDat + " "); } Console.WriteLine(); } -
我看到问题的发生是因为您在标题中的文件名中有一个点。在这里查看原因:stackoverflow.com/questions/2940618/…
-
哈!!!我把它去掉,看看会发生什么。谢谢!!!