使用 lambda 谓词比较两个列表以确定两个列表是否包含相同的项目

如果我的对象列表包含 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());

}

编辑,感谢所有快速回答,我看到有几种方法可以做到这一点,现在对表达式中发生的事情有了更好的理解。


拉莫斯之舞
浏览 202回答 5
5回答

当年话下

尝试var containsAllTypes = typeList.All(x => wList.Select(x => x.bearing).Contains(x))

绝地无双

var&nbsp;containsAll&nbsp;=&nbsp;typeList.All(type&nbsp;=>&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;wList.Any(widget&nbsp;=>&nbsp;widget.bearing.Equals(type)));翻译后,对于所有类型typeList来说,列表中的任何(至少一个)小部件都具有该类型。

沧海一幻觉

我相信您想要的是以下内容:bool&nbsp;containsAllTypes1&nbsp;=&nbsp;wList.TrueForAll(a&nbsp;=>&nbsp;null&nbsp;!=&nbsp;typeList.Find(b&nbsp;=>&nbsp;b&nbsp;==&nbsp;a.bearing));您还可以使用 System.Linq,如下所示:bool&nbsp;containsAllTypes2&nbsp;=&nbsp;wList.All(a&nbsp;=>&nbsp;typeList.Any(b&nbsp;=>&nbsp;b&nbsp;==&nbsp;a.bearing));

繁花不似锦

较短的是containsAllTypes&nbsp;=&nbsp;wList.Where(x&nbsp;=>&nbsp;typeList.Contains(x.bearing)).Count()&nbsp;==&nbsp;typeList.Count;或者containsAllTypes&nbsp;=&nbsp;&nbsp;wList.Select(x&nbsp;=>&nbsp;x.bearing).Except(typeList).Count()&nbsp;==&nbsp;0;或者containsAllTypes&nbsp;=&nbsp;&nbsp;wList.Select(x&nbsp;=>&nbsp;x.bearing).Intersect(typeList).Count()&nbsp;==&nbsp;typeList.Count;

森栏

Dim&nbsp;containsAllTypes&nbsp;As&nbsp;Boolean&nbsp;=&nbsp;wList.All(Function(a)&nbsp;typeList.Any(Function(b)&nbsp;b&nbsp;=&nbsp;a.bearing))对于 wList 中的每个值,它会检查 typeList 中的任何值是否与 wList 方位值匹配。
打开App,查看更多内容
随时随地看视频慕课网APP