【发布时间】:2015-02-19 04:37:57
【问题描述】:
编辑
我最初的问题不是很清楚,所以我想现在改一下。如果我仍然错过标记,请告诉我。
本质上,我正在尝试返回一个新字符串,其中所有用括号括起来的子字符串都已替换为列表中对象的字符串。作为一个抽象的例子,我想做如下的事情:
public class MyType () : IEquatable <Property>
{
public string id;
public override String ToString()
{
return id;
}
public bool Equals ( MyType other )
{
if ( other is MyType == false )
{
return false;
}
return this.id == other.id;
}
}
List<MyType> listOfCustomTypes = new List<MyType> ();
return Regex.Replace ( originalString, "{(.*?)}", d => listOfCustomTypes.Where ( t => t.id == d.Groups[1].Value ).FirstOrDefault ());
具体来说,我遇到的问题或错误是Cannot convert lambda expression to delegate type (System.Text.RegularExpressions.MatchEvaluator) because some of the return types in the block are not implicitly convertible to the delegate return type。
我假设它不允许在委托中使用返回类型,或者其他什么,因为我通常可以访问它的属性,或者转换为字符串。
我可能仍然设法弄乱了我的问题,所以如果它有帮助,我的完整项目可以看到here,这个问题的相关文件是here(具体行是 161)。
原始问题
我正在尝试学习如何使用委托和 lambda,并且以典型的方式,我无法咀嚼。在下面的代码 sn-p 中,我定义了一个类,其中包含一个类列表。在另一个函数中,我尝试使用字符串来查找列表项,并从该项中获取值。
[XmlRoot ( "Replacers" )]
public class Replacers
{
[XmlElement ( "Property" )]
public List<Property> properties = new List<Property> ();
[XmlIgnore]
public static Replacers replacers;
}
public class Property : IEquatable <Property>
{
[XmlAttribute ( "id" )]
public string id;
[XmlElement ( "Value" )]
public List<Value> propertyValue = new List<Value> ();
public override String ToString()
{
return id;
}
public bool Equals ( Property other )
{
return this.id == other.id && this.propertyValue == other.propertyValue;
}
}
public static class GetVariable
{
public static string FromUser ( string originalString )
{
try
{
//return Regex.Replace ( originalString, "{(.*?)}", m => Replacers.replacers.properties.FindIndex ( m.Groups[1].Value ) );
} catch ( Exception e )
{
return "ERROR: Unable to find '" + Regex.Match ( originalString, "{(.*?)}" ) + "'";
}
}
}
上面注释掉的行是我试图弄清楚。如何将与模式 {(.*?)} 匹配的任何内容替换为同名列表项中的值。
感谢您花时间考虑我的问题!
TL;DR:
如何使用 lambda 迭代列表,其中迭代返回实际的列表项?例如,我想做类似的事情:Regex.Replace ( input, pattern, m => myList.Where(listItem.identifier == m)。我觉得我的问题不是很清楚,所以如果您感到困惑,请询问。谢谢!
【问题讨论】: