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

时间:2019-03-06 19:09:19

标签: c# .net vb.net lambda predicate

如果我的对象列表包含vb.net或C#中的类型列表中的所有类型,我试图返回一个布尔值。我正在努力编写一个lambda表达式来完成此任务。可以使用lambda谓词完成此操作吗?我知道每个循环都可以轻松完成。

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());
}

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

6 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

var containsAll = typeList.All(type => 
    wList.Any(widget => widget.bearing.Equals(type)));

已翻译,对于typeList中的所有类型,列表中的任何(至少一个)小部件都具有该类型。

答案 2 :(得分:2)

我相信您想要的是以下内容:

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));

答案 3 :(得分:1)

较短的是

containsAllTypes = wList.Where(x => typeList.Contains(x.bearing)).Count() == typeList.Count;

containsAllTypes =  wList.Select(x => x.bearing).Except(typeList).Count() == 0;

containsAllTypes =  wList.Select(x => x.bearing).Intersect(typeList).Count() == typeList.Count;

答案 4 :(得分:1)

 Dim containsAllTypes As Boolean = wList.All(Function(a) typeList.Any(Function(b) b = a.bearing))

对于wList中的每个值,它都会检查typeList中的任何值是否与wList方位值匹配。

答案 5 :(得分:0)

您可以使用Intersect检查两个列表是否具有相同的值。试试这个代码

var hasAll = wList
 .Select(w => w.bearing)
 .Distinct()
 .Intersect(typeList)
 .Count() == typeList.Count;

如果仅在hasAll == true中的所有类型都出现一次时才需要拥有wList,请删除对Distinct的呼叫