我建议
1)创建一个包含点的对象,
2)模块化解析字符串的部分(最好在一个类中,但可以使用方法),
3)然后使用 LINQ 获取所有行的值您寻找的专栏
一个例子如下:
void Main()
{
const string columnName = "ColumnYouSeek";
var dgv = GetDataGridView(columnName);
var items = GetItems(dgv, columnName);
// items now contains what you want
}
创建一个对象来保存你的值
class ItemWithIndex
{
public string Text { get; set; }
public int StartIndex { get; set; }
public int EndIndex { get; set; }
public override string ToString()
{
return string.Format(
"{0}: Starts at {1}, Ends at {2}",
Text, StartIndex, EndIndex);
}
}
更改为下面以指向您的 DataGridView
public System.Windows.Forms.DataGridView GetDataGridView(string columnName)
{
var dgv = new System.Windows.Forms.DataGridView();
var column = new System.Windows.Forms.DataGridViewTextBoxColumn();
column.DataPropertyName = columnName;
column.Name = columnName;
dgv.Columns.Add(column);
dgv.Rows.Add("-cat--dog----");
dgv.Rows.Add("--elephant----mouse----");
return dgv;
}
模块化获取物品
public IEnumerable<ItemWithIndex> GetItems(
System.Windows.Forms.DataGridView dgv, string columnName)
{
var rows = dgv.Rows.Cast<System.Windows.Forms.DataGridViewRow>();
var rowData = rows.Select(x => (x.Cells[columnName].Value ?? "").ToString());
return rowData.SelectMany(x => GetWords(x));
}
模块化部分以获得单个单词
注意:这可以进行单元测试和重构
public IEnumerable<ItemWithIndex> GetWords(string val)
{
var index = val.IndexOf("-");
while (index >= 0 && index + 1 < val.Length)
{
var startIndex = index + 1;
var endIndex = val.IndexOf("-", startIndex);
if (endIndex < 0)
endIndex = val.Length - 1; // end of string
var text = val.Substring(startIndex, endIndex - startIndex);
index = endIndex;
if (string.IsNullOrEmpty(text))
continue;
yield return new ItemWithIndex
{
Text = text,
StartIndex = startIndex,
EndIndex = endIndex,
};
}
}