按范围过滤字符串

时间:2016-07-18 03:34:29

标签: c# entity-framework linq

如何按数字范围过滤字符串。

  

例如:0001 =< x =< 0010

其中 x 是字符串:“AAA-SomeText- 0005

0001 - 0010是范围

3 个答案:

答案 0 :(得分:1)

您可以使用以下代码段。设stringList为具有输入值的字符串列表:

List<string> stringList = new List<string>()
{
"AAA-SomeText-00015",
"AAA-SomeText-00025",
"AAA-SomeText-00019",
"AAA-SomeText-0005",
"AAA-SomeText-0006",
"AAA-SomeText-0007",
"AAA-SomeText-0008",
"AAA-SomeText-0009",
"AAA-SomeText-00010",
"AAA-SomeText-00011",
"AAA-SomeText-00012",
"AAA-SomeText-00013"
};

然后,您将使用以下代码获取过滤列表:

int minRange = 1;
int maxRange = 10;
var subList = stringList.Select(x => new { index = int.Parse(x.Substring(x.LastIndexOf("-") + 1)), value = x })
                        .Where(x => x.index > minRange && x.index < maxRange)
                        .Select(i=>i.value).ToList();

答案 1 :(得分:1)

试试这个,

List<string> stringList = new List<string>()
{
   "AAA-SomeText-00015",
   "AAA-SomeText-00025",
   "AAA-SomeText-00019",
   "AAA-SomeText-0005",
   "AAA-SomeText-0006",
   "AAA-SomeText-0007",
   "AAA-SomeText-0008",
   "AAA-SomeText-0009",
   "AAA-SomeText-00010",
   "AAA-SomeText-00011",
   "AAA-SomeText-00012",
   "AAA-SomeText-00013"
};

foreach (string text in stringList)
{
      if (int.Parse(text.Split('-')[2]) >= 0001 && int.Parse(text.Split('-')[2]) <= 0010)
      {
            // find filtered numbers
      } 
}

答案 2 :(得分:1)

将其拆分为-并取最后一个值并进行比较。以下是该片段。

string strRange = "AAA-SomeText-0005";
int val = int.Parse(strRange.Split('-')[2]); //in val you get the last number.