English 中文(简体)
C#将元素拆分为多个元素
原标题:C# Splitting Element Into Multiple Elements
  • 时间:2010-10-22 00:58:45
  •  标签:
  • c#
  • list

我有一个对象数组/列表/集合等。出于示例的目的,假设它只是一个字符串数组/list/collection等。

我想遍历数组,并根据某些条件拆分某些元素。这一切都由我的对象处理。因此,一旦我有了要拆分的对象索引,拆分对象然后按顺序将其重新插入原始数组的标准方法是什么。我将尝试使用字符串数组来演示我的意思:

string[] str = { "this is an element", "this is another|element", "and the last element"};
List<string> new = new List<string>();

for (int i = 0; i < str.Length; i++)
{
    if (str[i].Contains("|")
    {
          new.AddRange(str[i].Split("|"));
    }
    else
    {
          new.Add(str[i]); 
    }
}

//new = { "this is an element", "this is another", "element", "and the last element"};

这段代码很有效,但有更好的方法吗?是否有已知的设计模式;就像一个原地数组分裂?

最佳回答

对于这个特定的示例,您可以使用SelectMany来获得新的数组。

string[] array = { "this is an element", "this is another|element", "and the last element" };
string[] newArray = array.SelectMany(s => s.Split( | )).ToArray();
// or List<string> newList = array.SelectMany(s => s.Split( | )).ToList();
// or IEnumerable<string> projection = array.SelectMany(s => s.Split( | ));
问题回答

您可以这样做:

List<string> newStr = str.SelectMany(s => s.Split( | )).ToList();




相关问题
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. ...

热门标签