SO I have a DataTable with a few fields populated from Rest (not all listed), I have a treeview populated with delineated tree from path in the DT. I want to be able to select any portion of the tree and generate an array of the all the matches. Problem I'm running into is that if I search for M19, I get everything that contains M19... including M198. I can make this work with parsing out the Path and doing an exact... but it's really ugly and very slow and add an entire new loop. Is there a more elegant way to code this?
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
CodePudding user response:
You can split the Path
field by the \
and -
separators to create a string array and search the substrings for a given branch or node:
//
// 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();
Alternatively, use RegEx
to search the Path
field for a match. Append \b
to the given branch to create a whole-word-search pattern (i.e. m19\b
) to skip the other branches like M198
. Online Test.
//
// 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();
Either way, calling:
var s = "m19";
Console.WriteLine(string.Join(", ", GetTreeBranch(locationData, s)));
Yields:
Main\M19, Main\M19\M19-I1, Main\M19\M19-I2