简体   繁体   中英

How can I extract words from a comma-separated string using LINQ?

I have a string like:

string features="name1,name2,name3,name4,name5,name6,name7";

Now I want to extract all names and store the results in a string array using LINQ. Is this possible?

If not then please tell me the easiest method for doing this.

I have done it like this, but want to do it using LINQ.

string Allfeat = txtFeatures.Text;
string sep = ",";
string[] feat = Allfeat.Split(sep.ToCharArray());

This is the easiest:

string[] feat  = Allfeat.Split(',');

LINQ is awesome and very useful for most cases.But you don't have to use LINQ all the time.In this case there are several overloaded versions of Split method.One of them takes params char[] as parameter so you can easily pass zero or more seperators.Also in your case if you want to simplify it you don't need that Allfeat variable, you can use txtFeatures.Text directly.

string[] feat = txtFeatures.Text.Split(',')

You could roll your own in Linq, like so:

public static IEnumerable<string> CsvSplit( this IEnumerable<char> text , char delimiter = ',' )
{
  StringBuilder sb = new StringBuilder() ;
  foreach ( char c in text )
  {
    if ( c == delimiter )
    {
      yield return sb.ToString() ;
      sb.Length = 0 ;
    }
    else
    {
      sb.Append(c) ;
    }
  }
  if ( sb.Length > 0 )
  {
    yield return sb.ToString() ;
  }
}

Or you could use regular expressions, something along these lines:

private static Regex rxWord = new Regex( @"[^,]*") ;
public static IEnumerable<string> CsvSplit( this string text )
{
  for ( Match m = rxWord.Match(text) ; m.Success ; m = m.NextMatch() )
  {
    yield return m.Value ;
  }
}

But what's wrong with string.Split() ? Though, parsing anything but a trivial CSV text isn't as simple as it might seem :D — you might want to look at using Sebastien Lorion's most excellent Fast CSV Reader :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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