简体   繁体   English

用C#中的数组的特定部分来做事

[英]Do things with specific part of array in C#

I am not sure about foreach, maybe I need to create new "Bob array"? 我不确定foreach,也许我需要创建新的“鲍勃数组”?

string[] array = new string[] {"Andrew 11312", "23214 Bob", "123 John", "Bob 222"}
foreach (var i /*which contains "Bob" */ in array)
{do things}

You can use LINQ to achieve this. 您可以使用LINQ实现此目的。

foreach (var bob in array.Where(i => i.Contains("Bob")))
{
    // Do stuff with Bob ...
}

This requires the following namespace: using System.Linq; 这需要以下名称空间: using System.Linq;

If you need to modify the parts that contain "Bob" then you can do it with Select() . 如果需要修改包含"Bob"的零件,则可以使用Select()

 array = array.Select((i) =>
 {
     if (i.Contains("Bob"))
     {
         // Modify i, because it contains "Bob"
     }

     return i;
}).ToArray();
for (Int32 i = 0; i < array.Length; ++i)
{
    String s = array[i];

    if (!s.Contains("Bob"))
        continue;

    // do what you have to do...
}

Or, as well: 或者,也:

foreach (String s in array)
{
    if (!s.Contains("Bob"))
        continue;

    // do what you have to do...
}

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

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