English 中文(简体)
更改每个相向环到 LINQ 查询
原标题:Change the foreach loop into the LINQ query
  • 时间:2012-05-22 16:54:31
  •  标签:
  • c#
  • linq

我被困在一个简单的设想中。 我有一个 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

现在,我想知道该如何改变这个循环到 LINQ 查询中。 有什么想法吗?

  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;

尝试此 :

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();

这是一种不同的做法:

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

您可能需要在索引中添加一个+1, 但我不确定 。

它的作用是:

  • Removes the first item (that s the substring for). In your example, it should be "1_2_3_4_5_generatedGUID"
  • Checks the string starts with what you are expecting. In your example: 1_2_

< 加固 > 编辑后: 在第一个“ 位置” 时添加任何文件的样式

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




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签