如果我的对象列表包含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 SubC#
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());
}编辑,感谢你的快速回答,我看到有几种方法可以做到这一点,现在对表达式中发生的事情有了更好的理解。
发布于 2019-03-07 03:17:31
var containsAll = typeList.All(type =>
wList.Any(widget => widget.bearing.Equals(type)));经过转换,对于typeList中的所有类型,列表中的任何(至少一个)小部件都具有该类型。
发布于 2019-03-07 03:25:41
试试var containsAllTypes = typeList.All(x => wList.Select(x => x.bearing).Contains(x))
发布于 2019-03-07 03:26:51
我相信你想要的是:
bool containsAllTypes1 = wList.TrueForAll(a => null != typeList.Find(b => b == a.bearing));您还可以按如下方式使用System.Linq:
bool containsAllTypes2 = wList.All(a => typeList.Any(b => b == a.bearing));https://stackoverflow.com/questions/55030513
复制相似问题