【发布时间】:2016-04-25 06:56:22
【问题描述】:
我有一个包含各种类型元素的数组。
我正在尝试构建一个 lambda 表达式,如果数组中存在特定类型,它将评估 if 子句为 true。
我尝试了以下和许多不同的方法,但我似乎没有做对:
var arraySourceText = EditorController.ActiveDocument
.ActiveSegmentPair
.Source
.AllSubItems
.ToArray();
if (arraySourceText.Any(o => o.GetType()) == typeof(string))
{
intStartingPH++;
}
欢迎任何建议。
注意:arraySourceText 是具有自定义类型的 API IEnumerable。为简单起见,我只是假设string 在伪代码中。
更新:因为 API 没有公开类型,只有类型的名称,解决方法是基于 Byyo 的更正。我写了一个单独的方法来检查类型的名称并返回一个bool:
var arraySourceText = EditorController.ActiveDocument
.ActiveSegmentPair
.Source
.AllSubItems
.ToArray();
string typePH = "PlaceholderTag";
if (arraySourceText.Any(o => IsMatchTypeString(typePH, o)))
{
intStartingPH++;
}
//Then the below method does the check:
static bool IsMatchTypeString(string testtype, params object[] items)
{
if (items.Length == 0)
{
return false;
}
else if (testtype == items[0].GetType().ToString())
{
return true;
}
else
{
return false;
}
}
【问题讨论】:
-
你的括号错了(虽然可能是错字):
arraySourceText.Any(o => o.GetType()== typeof(string) -
感谢回复,我添加了数组的声明和澄清说明。
标签: c# arrays visual-studio plugins lambda