我可以在LINQ查询中使用正则表达式或调用方法吗?

时间:2016-06-06 09:43:18

标签: c# linq

我有这个LINQ查询:

var webWordForms = 
   .Select(def => new WebWordForm
   {
       definition = def.definition,
       partOfSpeech = definition.partOfSpeech,
       sourceId = 1,
       synonyms = def.synonyms
   })
   .ToList();

这是WebWordForm类:

public class WebWordForm
{
    public string definition { get; set; }
    public string partOfSpeech { get; set; }
    public int sourceId { get; set; }
    public List<string> examples { get; set; }
}

我需要做的是解析查询的def.definition部分中包含的数据,并将其放入两个属性:definition和examples。

这是def.definition中典型数据的一个示例。每个例子之间都有一个空行。

 the trait of lacking restraint or control; freedom from inhibition or worry; "she danced with abandon"

 a feeling of extreme emotional intensity; "the wildness of his anger"

 forsake, leave behind; "We abandoned the old car in the empty parking lot"

 stop maintaining or insisting on; of ideas, claims, etc.; "He abandoned the thought of asking for her hand in marriage"; "Both sides have to give up some calims in these negociations"

 give up with the intent of never claiming again; "Abandon your life to God"; "She gave up her children to her ex

 leave behind empty; move out of; "You must vacate your office by tonight"

 leave someone who needs or counts on you; leave in the lurch; "The mother deserted her children"

以下是对数据的解释:

  1. 直到; "为定义的数据的第一部分。
  2. 第一个; "之后的其余数据是一个或多个列表示例
  3. 我需要的是:

    1. 对于要转换的定义,所以第一个字符是大写字母,并且要进入:public string definition { get; set; }#1

    2. 对于此后的示例:public List<string> examples { get; set; }#2

    3. 实施例

      var webWordForms = 
         .Select(def => new WebWordForm
         {
             definition = #1
             examples = #2
             partOfSpeech = definition.partOfSpeech,
             sourceId = 1,
             synonyms = def.synonyms
         })
         .ToList();
      

      我知道这不是一个简单的问题,但我很感激有关如何做到这一点的任何意见和建议

1 个答案:

答案 0 :(得分:3)

有可能,你可以这样做。

var webWordForms = webforms  // this was just added, use actual collection.
   .Select(def => 
    { 
       string[] splits = def.definition.Split(new string[] {@"; """}, StringSplitOptions.RemoveEmptyEntries);
       return new WebWordForm
       {

           definition = splits[0],
           examples =  splits.Skip(1).ToList(),
           partOfSpeech = definition.partOfSpeech,
           sourceId = 1,
           synonyms = def.synonyms
       }
    })
   .ToList();