string[] lines = File.ReadAllLines(@"c:\wmiclasses\wmiclasses1.txt");
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].StartsWith("ComboBox"))
{
}
}
这就是文本文件内容的样子:
ComboBox Name cmbxOption
Classes Win32_1394Controller
Classes Win32_1394ControllerDevice
ComboBox Name cmbxStorage
Classes Win32_LogicalFileSecuritySetting
Classes Win32_TapeDrive
我需要做的是做一些事情:
ComboBox
开头,然后仅从该行中获取ComboBox
名称,例如cmbxOption
。由于我的ComboBoxes
设计师已经有form1
,因此我需要确定cmbxOption
开始和结束的位置以及下一个ComboBox
开始cmbxStorage
的时间点
要获取当前ComboBox
的所有行,例如此行属于cmbxOption
:
类Win32_1394Controller 类Win32_1394ControllerDevice
要从每一行创建一个Key和Value,例如从行:
创建类Win32_1394Controller
然后该密钥将为Win32_1394Controller
,且该值仅为1394Controller
然后是第二行键Win32_1394ControllerDevice
,仅值1394ControllerDevice
要向正确的归属ComboBox添加值1394Controller
。
如果我在ComboBox
中选择cmbxOption
项目1394Controller
时,我会选择Win32_1394Controller
。
例如在这个事件中:
private void cmbxOption_SelectedIndexChanged(object sender, EventArgs e)
{
InsertInfo(cmbxOption.SelectedItem.ToString(), reflstDisplayHardware, chkHardware.Checked);
}
需要SelectedItem
为Win32_1394Controller
,但用户只会在cmbxOption
1394Controller
中看到Win32_
这是方法InsertInfo
的开始 private void InsertInfo(string Key, ref ListView lst, bool DontInsertNull)
{
这就是为什么我需要Key将是Win32_1394Controller,但我希望用户只能在ComboBox
1394Controller
中看到Win32_
答案 0 :(得分:0)
这是一些快速丑陋的代码:
class Group<T> : List<T>, IGrouping<T, T>
{
public T Key { get; private set; }
public Group(T key)
{
Key = key;
}
}
static class Extensions
{
public static IEnumerable<IGrouping<string, string>> GroupByComboboxName(this IEnumerable<string> lines)
{
Group<string> group = null;
foreach (var line in lines)
{
if (string.IsNullOrWhiteSpace(line)) continue;
var parts = line.Split(' ');
if (parts.Length == 3 && parts[0] == "ComboBox" && parts[1] == "Name")
{
if (group != null) yield return group;
group = new Group<string>(parts[2]);
}
else if (group != null)
{
group.Add(line);
}
}
if (group != null) yield return group;
}
}
如何使用它:
var lines = @"ComboBox Name cmbxOption
Classes Win32_1394Controller
Classes Win32_1394ControllerDevice
ComboBox Name cmbxStorage
Classes Win32_LogicalFileSecuritySetting
Classes Win32_TapeDrive".Split('\n').Select(l => l.TrimEnd('\r')).ToArray();
lines.GroupByComboboxName().ForEach(g =>
{
Console.WriteLine(g.Key + ":");
g.ForEach(l => Console.WriteLine(" " + l));
});
它产生的输出:
cmbxOption:
Classes Win32_1394Controller
Classes Win32_1394ControllerDevice
cmbxStorage:
Classes Win32_LogicalFileSecuritySetting
Classes Win32_TapeDrive
这应该让你去。