简体   繁体   English

如何使用LINQ从逗号分隔的字符串中提取单词?

[英]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. 现在,我想提取所有名称,然后使用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. 我已经这样做了,但是想用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. LINQ非常棒,并且在大多数情况下非常有用。但是您不必一直使用LINQ 。在这种情况下, Split有多个重载版本。其中一个使用params char[]作为参数,因此您可以轻松地传递zeromore分隔符。如果您要简化分隔符,则不需要Allfeat变量,则可以直接使用txtFeatures.Text

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

You could roll your own in Linq, like so: 您可以像这样在Linq中推出自己的产品:

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() ? 但是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 : 但是,解析琐碎的CSV文本并不像看起来那么简单:D-您可能想看看使用Sebastien Lorion最出色的Fast CSV Reader

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

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