[英]Matching values in a list collection and values in the DataTable row in C#
[英]c# wildcards not matching datatable column values
我在嘗試將數據表列名與包含通配符的字符串匹配時遇到問題。
我有一個帶有各種列名的數據表,其中包括一組名稱,如下所示:“ PsA”,“ PsB”,“ PsC”等。 我想遍歷標題中包含Ps的所有列,並使用這些標題提取數據。
我目前有以下代碼,無法返回任何匹配項。 我在if語句(“ PsA”)中將一個直接值替換為測試,這很好用; 但是,當我使用通配符時,沒有匹配項。 我也沒有運氣嘗試過正則表達式。
private void dfaSection_SelectedIndexChanged(object sender, EventArgs e)
{
string psText = null;
string colID = "Ps*";
offBox.Text = ""; //Clear textbox if a reselection occurs
psBox.Text = ""; //Clear textbox if a reselection occurs
info.offTitle = dfaSection.Text; //Set textbox from variable
dt = opr.findOffByTitle(info); //Get datatable from SQL database
if(dt.Rows.Count > 0)
{
offBox.Text = dt.Rows[0][5].ToString(); //Set textbox from datatable
foreach(DataColumn dc in dt.Columns) //Loop through datatable columns
{
if (dc.ColumnName.ToString() == colID) //Check that column title matches test string - Later addition--> && dt.Rows[0][dc].ToString() != null)
{
psText = dt.Rows[0][dc].ToString() + "\n\n"; //Add data from matched column to string variable
}
}
psBox.Text = psText; //Set textbox from variable
}
}
編輯:使用.Contains(colID)
列名現在已匹配,字符串現在未加載到psText
變量,但是我將花一些時間來使其工作。 感謝Skaros Ilias。
我對C不太滿意,但是==
肯定不是正確的方法。 您需要使用contains
方法。 如我所說,我並不熟悉它,但是文檔中有一個很好的例子。
String s = "This is a string.";
String sub1 = "this";
Console.WriteLine("Does '{0}' contain '{1}'?", s, sub1);
StringComparison comp = StringComparison.Ordinal;
Console.WriteLine(" {0:G}: {1}", comp, s.Contains(sub1, comp));
按照此答案之前: 正則表達式通配符
這是代碼示例:
private static bool Match(string pattern, string stringToCheck) {
var finalPattern = pattern.Replace("*", ".*?");
Regex regex = new Regex(finalPattern);
return regex.IsMatch(stringToCheck);
}
在斷點檢查斷點,檢查列名和colID
是什么。當什至不知道值時,如何解決問題? 使用dc.ColumnName.ToString().StartsWith()
。 Contains()
僅在字符串以結束時才有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.