简体   繁体   English

将foreach循环更改为LINQ查询

[英]Change the foreach loop into the LINQ query

I stuck in an easy scenario. 我陷入了一个简单的情况。 I have a List<string> object, all of its items has the body of: 我有一个List<string>对象,其所有项目的主体为:

item_1_2_generatedGUID //generatedGUID is Guid.NewGuid()

but there may be much more numbers item_1_2_3_4_5_generatedGUID etc 但可能会有更多的数字item_1_2_3_4_5_generatedGUID

now, I'm wondering how to change that loop into the LINQ's query. 现在,我想知道如何将循环更改为LINQ的查询。 Any ideas ? 有任何想法吗 ?

  string one = "1"; //an exaplme
  string two = "2"; //an exaplme

  foreach (var item in myStringsList)
  {
      string[] splitted = item.Split(new char[] { '_' },
                                     StringSplitOptions.RemoveEmptyEntries);

      if(splitted.Length >= 3)
      {
          if(splitted[1] == one && splitted[2] == two)
          {
              resultList.Add(item);
          }
      }
  }
var result = from s in lst 
             let spl = s.Split('_')
             where spl.Length >= 3 && spl[1] = one  && spl[2] == two
             select s;

Try this: 尝试这个:

var query = from item in myStringsList
            let splitted = item.Split(new[] { '_' }, SSO.RemoveEmptyEntries)
            where splitted.Length >= 3
            where splitted[1] == one && splitted[2] == two
            select item;

var resultList = query.ToList();

This is a different approach: 这是一种不同的方法:

var items = myStringsList.
            Where(x => x.Substring(x.IndexOf("_")).StartsWith(one+"_"+two+"_"));

You probably will need to add a +1 in the IndexOf, but I'm not sure. 您可能需要在IndexOf中添加+1,但是我不确定。

What it does is: 它的作用是:

  • Removes the first item (that's the substring for). 删除第一项(这是其的子字符串)。 In your example, it should be "1_2_3_4_5_generatedGUID" 在您的示例中,它应该是“ 1_2_3_4_5_genicGUID”
  • Checks the string starts with what you are expecting. 检查字符串是否以您期望的开头。 In your example: 1_2_ 在您的示例中:1_2_

编辑:在第一个“位置”添加了任何内容的模式

var result = items.Where(i => Regex.IsMatch(i, "^[^_]_1_2_"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM