人物解读

时间:2017-08-30 11:58:19

标签: c# linq

我想定义写的字符。 我认为举一个例子可以更容易解释。

样品;

      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

这是我搜索明星字符的方式。

1 个答案:

答案 0 :(得分:1)

您正在寻找通配符,您可以将其转换为相应的*正则表达式,请参阅

Matching strings with wildcard

E.g。

  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;

然后像往常一样使用正则表达式

StartsWith

请注意,使用外卡时,ContainsEndsWithvar accountFound = account .Select(a => a.accountName) .SelectMany(acc => Regex .Matches(acc, WildCardToRegular(search)) .OfType<Match>() .Where(match => match.Success) .Select(match => match.Value)) .FirstOrDefault(); 不需要

修改:如果您想要匹配的值,只需修改查询:

function changeText(){
  if (document.getElementById("morecat").innerHTML === '1'){
      document.getElementById("morecat").innerHTML = '2';
   }
  else {
     document.getElementById("morecat").innerHTML = '1';
  }
}