所以我有一個 DataTable,其中包含從 Rest 填充的幾個欄位(未列出全部),我有一個樹視圖,其中填充了 DT 中路徑的描繪樹。我希望能夠選擇樹的任何部分并生成所有匹配項的陣列。我遇到的問題是,如果我搜索 M19,我會得到包含 M19 的所有內容......包括 M198。我可以通過決議路徑并做一個精確的作業來完成這項作業......但它真的很難看而且非常慢并且添加了一個全新的回圈。有沒有更優雅的編碼方式?
Sample Code:
public string[] GetNodeID(string locName)
{
var results = from myRow in locationData.AsEnumerable()
where myRow.Field<string>("Path").ToUpper().Contains(locName.ToUpper())
select myRow;
DataView view = results.AsDataView();
return null;
}
Example Tree
Main
->M19
-> ->M19-I1
-> ->M19-I2
-> M198
-> -> M198-I1
-> -> M198-I2
locationData Table
ID Path Description
0 Main\M19 Null
1 Main\M19\M19-I1 Instrument 1
2 Main\M19\M19-I2 Instrument 2
3 Main\M198\M198-I1 Instrument 1
4 Main\M198\M198-I2 Instrument 2
uj5u.com熱心網友回復:
您可以通過and分隔符拆分Path欄位以創建字串陣列并搜索給定分支或節點的子字串:\-
//
// using System.Linq;
public string[] GetTreeBranch(DataTable dt, string branch) => dt.AsEnumerable()
.Where(x => x.Field<string>("Path").Split('\\', '-')
.Any(y => y.Equals(branch, StringComparison.OrdinalIgnoreCase)))
.Select(x => x.Field<string>("Path")).ToArray();
或者,用于RegEx在欄位中搜索Path匹配項。附加\b到給定的分支以創建全詞搜索模式(即m19\b)以跳過其他分支,例如M198. 在線測驗。
//
// using System.Text.RegularExpressions;
public string[] GetTreeBranch(DataTable dt, string branch) => dt.AsEnumerable()
.Where(x => Regex.IsMatch(
x.Field<string>("Path"), $@"{branch}\b", RegexOptions.IgnoreCase))
.Select(x => x.Field<string>("Path")).ToArray();
無論哪種方式,呼叫:
var s = "m19";
Console.WriteLine(string.Join(", ", GetTreeBranch(locationData, s)));
產量:
Main\M19, Main\M19\M19-I1, Main\M19\M19-I2
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438276.html
上一篇:兩個集合類之間的流利斷言
下一篇:哪種HTTP狀態碼適合這種情況?
