【发布时间】:2019-03-06 19:09:18
【问题描述】:
如果我的对象列表包含 vb.net 或 C# 中类型列表中的所有类型,我将尝试返回一个布尔值。我正在努力编写一个 lambda 表达式来实现这一点。这可以使用 lambda 谓词来完成吗?我知道使用 for each 循环可以轻松完成。
vb.net
Public Class Widget
Public wobbly As String
Public sprocket As String
Public bearing As String
End Class
Public Sub test()
Dim wList As New List(Of Widget)
wList.Add(New Widget() With {.bearing = "xType", .sprocket = "spring", .wobbly = "99"})
wList.Add(New Widget() With {.bearing = "yType", .sprocket = "sprung", .wobbly = "45"})
wList.Add(New Widget() With {.bearing = "zType", .sprocket = "straight", .wobbly = "17"})
Dim typeList As New List(Of String) From {"xType", "yType", "zType"}
Dim containsAllTypes As Boolean = wList.TrueForAll(Function(a) a.bearing.Equals(typeList.Where(Function(b) b = a.bearing)))
Debug.WriteLine(containsAllTypes.ToString)
End Sub
C#
public class Widget
{
public string wobbly;
public string sprocket;
public string bearing;
}
public void test()
{
List<Widget> wList = new List<Widget>();
wList.Add(new Widget {
bearing = "xType",
sprocket = "spring",
wobbly = "99"
});
wList.Add(new Widget {
bearing = "yType",
sprocket = "sprung",
wobbly = "45"
});
wList.Add(new Widget {
bearing = "zType",
sprocket = "straight",
wobbly = "17"
});
List<string> typeList = new List<string> {
"xType",
"yType",
"zType"
};
bool containsAllTypes = wList.TrueForAll(a => a.bearing.Equals(typeList.Where(b => b == a.bearing)));
Debug.WriteLine(containsAllTypes.ToString());
}
编辑,感谢所有快速回答,我看到有几种方法可以做到这一点,现在对表达式中发生的事情有了更好的理解。
【问题讨论】:
-
如果
wList包含两个带有xType的项目怎么办?您当前的代码有什么问题?你能展示(在 c# 伪代码中)你想要达到的目标吗?
标签: c# .net vb.net lambda predicate