[英]C# Extension method to Convert into the comma separated
我有一些數據,例如name,firstname,surname,std,Rollno
。
使用 C#,我想將其轉換為
('name', 'surname', 'std', 'Rollno')
這樣我就可以使用這些數據來查詢 SQL/MySQL 數據庫,例如 -
SELECT *
FROM Table1
WHERE UserCommunicationId IN ('name', 'surname', 'std', 'Rollno');
代替
SELECT *
FROM Table1
WHERE UserCommunicationId IN ('name,surname,std,Rollno');
您可以嘗試以下邏輯
public static class SQLQueryExtensions
{
public static string ColumnFormat(this String str)
{
return "(" + //Include first parenthesis
string.Join(", ", str.Split().Select(x => $"'{x}'")) //Add single quote to each column
+ ")"; //Include last parenthesis
}
}
你也可以在一行中完成,
var inputStr = "name,firstname,surname,std,Rollno";
var result = "(" + string.Join(", ", inputStr.Split().Select(x => $"'{x}'")) + ")";
我可以提出的一種方法是:
我在下面寫了一個例子,但我是 Oracle 用戶,所以我不確定這些語法是否正確,甚至沒有經過測試,只是在谷歌上搜索了一下。 僅將其作為思想解釋的參考。
WITH RECURSIVE targets (stringBuffer, word) AS (
SELECT
@Parameter
,NULL
UNION ALL
SELECT
SUBSTRING_INDEX(stringBuffer, ',', -1)
,SUBSTRING_INDEX(stringBuffer, ',', 1)
WHERE LENGTH(word) > 0
OR LENGTH(stringBuffer) > 0 -- I am not really sure about these
)
SELECT *
FROM Table1
LEFT JOIN targets ON targets.word = Table1.UserCommunicationId
WHERE targets.word IS NOT NULL;
然后,在 C# 中,為您的查詢命令設置參數,如下所示
string s = "name,firstname,surname,std,Rollno";
或者,簡單地說:
SELECT *
FROM Table1
WHERE REGEXP_LIKE(UserCommunicationId, @Parameter)
;
將 C# 中的參數設置為:
string s = "name|firstname|surname|std|Rollno";
請注意,如果關鍵字可以由用戶輸入,您仍然存在用戶可以輸入.+的問題,並且只要沒有添加其他條件,它就會響應每個數據。
但就個人而言,如果您的查詢中確實需要未知長度的 IN-CLAUSE,我認為您的設計中存在潛在問題。 如果可以應用的關鍵字數量有限,粗略但這是我團隊當前的標准,您可以在 C# 中逐個關鍵字連接 WHERE 部分關鍵字。
使用打擊邏輯,將解決您的問題。
string inputStr = "name,firstname,surname,std,Rollno";
string result = string.Join(",", inputStr.Split(',').Select(x => string.Format("'{0}'", x)).ToList());
Output = 'name','firstname','surname','std','Rollno'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.