我认为您确实有两个问题,所以我将尝试分别回答。
第一个问题是“我怎样才能解析一个看起来像这样的文件...
DIRT: 3;
STONE: 6;
到名称和整数?”你可以从每一行中删除所有的空格和分号,然后在冒号上拆分。在我看来,更简洁的方法是使用正则表达式:
// load your file
var fileLines = new[]
{
"DIRT: 3;",
"STONE: 6;"
};
// This regular expression will match anything that
// begins with some letters, then has a colon followed
// by optional whitespace ending in a number and a semicolon.
var regex = new Regex(@"(\w+):\s*([0-9])+;", RegexOptions.Compiled);
foreach (var line in fileLines)
{
// Puts the tokens into an array.
// The zeroth token will be the entire matching string.
// Further tokens will be the contents of the parentheses in the expression.
var tokens = regex.Match(line).Groups;
// This is the name from the line, i.e "DIRT" or "STONE"
var name = tokens[1].Value;
// This is the numerical value from the same line.
var value = int.Parse(tokens[2].Value);
}
如果您不熟悉正则表达式,我鼓励您检查一下;它们使格式化字符串和提取值变得非常容易。 http://regexone.com/
第二个问题,“如何在名称旁边存储值?”,我不确定我是否完全理解。如果您要做的是用文件中指定的数值返回每个项目,dub stylee 的建议对您有好处。您需要将 name 作为显示成员,将 value 作为值成员。但是,由于您的数据不在表中,因此您必须将数据放在可访问的位置,以便可以命名您要使用的属性。我推荐一本字典:
// This is your ComboBox.
var comboBox = new ComboBox();
// load your file
var fileLines = new[]
{
"DIRT: 3;",
"STONE: 6;"
};
// This regular expression will match anything that
// begins with some letters, then has a colon followed
// by optional whitespace ending in a number and a semicolon.
var regex = new Regex(@"(\w+):\s*([0-9])+;", RegexOptions.Compiled);
// This does the same as the foreach loop did, but it puts the results into a dictionary.
var dictionary = fileLines.Select(line => regex.Match(line).Groups)
.ToDictionary(tokens => tokens[1].Value, tokens => int.Parse(tokens[2].Value));
// When you enumerate a dictionary, you get the entries as KeyValuePair objects.
foreach (var kvp in dictionary) comboBox.Items.Add(kvp);
// DisplayMember and ValueMember need to be set to
// the names of usable properties on the item type.
// KeyValue pair has "Key" and "Value" properties.
comboBox.DisplayMember = "Key";
comboBox.ValueMember = "Value";
在这个版本中,我使用了 Linq 来构建字典。如果您不喜欢 Linq 语法,可以使用循环代替:
var dictionary = new Dictionary<string, int>();
foreach (var line in fileLines)
{
var tokens = regex.Match(line).Groups;
dictionary.Add(tokens[1].Value, int.Parse(tokens[2].Value));
}