2017-08-30 97 views
0

我想定義寫入的字符。 我認爲通過舉例說明會更容易解釋。字符解釋

樣本;

 void Main(){ 
    List<account> account = new List<UserQuery.account>{ 
    new account() { accountCode = "100", accountName = "That is the house which I want. " }, 
    new account() { accountCode = "101", accountName = "I bought whatever you wanted" }, 
    new account() { accountCode = "102", accountName = "The flowers which you brought me were very beautiful."} 
    }; 

    string search = "*house*"; 
    string search2 = "The flowers*"; 
    string search3 = "*wanted."; 

    var result = account.FirstOrDefault(a => a.accountName.Contains(search)).accountCode; 
    var result2 = account.FirstOrDefault(a => a.accountName.StartsWith(search2)).accountCode; 
    var result3 = account.FirstOrDefault(a => a.accountName.EndsWith(search3)).accountCode; 
} 

public class account 
{ 
    public string accountCode { get; set; } 
    public string accountName { get; set; } 
} 



> result=100 
result2=102 
result3=101 

這是我如何搜索明星人物。

+4

你想完全定義什麼? – Isuka

+4

我不明白你的問題要麼 – Pikoh

+0

所以你想使用通配符來搜索,而不是'StartsWith','EndsWith'和'Contains'? – Silvermind

回答

1

您正在尋找通配符,你可以變成相應的*正則表達式,見

Matching strings with wildcard

例如

private static String WildCardToRegular(String value) { 
    return "^" + Regex.Escape(value).Replace("\\?", ".").Replace("\\*", ".*") + "$"; 
    } 

然後用正則表達式照常操作:

using System.Text.RegularExpressions; 

    ... 

    var result = account 
    .FirstOrDefault(a => Regex.IsMatch(a.accountName, WildCardToRegular(search))) 
    .accountCode; //TODO: what if the outcome of FirstOrDefault is null? 

    var result2 = account 
    .FirstOrDefault(a => Regex.IsMatch(a.accountName, WildCardToRegular(search2))) 
    .accountCode; 

    var result3 = account 
    .FirstOrDefault(a => Regex.IsMatch(a.accountName, WildCardToRegular(search3))) 
    .accountCode; 

請注意,沒有必要在StartsWithContains,與通配符

編輯工作時EndsWith如果你想要一個匹配的值,所有你需要的是修改y查詢:

var accountFound = account 
    .Select(a => a.accountName) 
    .SelectMany(acc => Regex 
    .Matches(acc, WildCardToRegular(search)) 
    .OfType<Match>() 
    .Where(match => match.Success) 
    .Select(match => match.Value)) 
    .FirstOrDefault(); 
+0

如果雙方都有清單,那麼如何應用一個公式陡峭。 即,如果我們想從列表中檢索值。 – KdrGny

+0

@KdrGny:如果你想檢索*匹配值*把'Regex.Matches'而不是'Regex.IsMatch' –