确定是否有任何 属性 值不为空并且与另一个列表中的值匹配

Determine if any property value is not null and matches value in another list

假设我有一个 List<string> 看起来像这样:

var lstStuff = new List<String>(){"test", "value", "other"};

我也有一个模型 Class 看起来像这样

public class Codes {
    public string Code     {get;set;}
    public string? HaveVal {get;set;}
}

在我的 C# 方法中,我有这样的东西。我想要实现的是 return TRUEFALSE 如果 lstStuff 中的任何单个项目在 lstCode[= 中有 HaveVal 21=]

public bool DoesAnyCodeHaveAValue
{
    var lstStuff = new List<String(){"Code1","Code2","Code3"};

    List<Code> lstCode = new List<Code>() {
                            new Code() {Code = "Code1", HaveVal=null},
                            new Code() {Code = "Code1", HaveVal="yes"},
                            new Code() {Code = "Code1", HaveVal="yes"}
                          };
 }

这是我实现此目的的代码,但我想知道是否有 LINQ 方法可以做到这一点。

 var isVal = false;

 foreach (var val in lstStuff){
    if (!string.IsNullOrEmpty(lstCode.Where(x=>x.Code=val).Select(y=>y.HaveVal).ToString())){
       isVal=true;
    }
 }

 return isVal;

有没有不需要循环的更短的方法?

您可以使用 Any() 两次::

bool isVal = lstCode.Any(c => lstStuff.Any(s => s == c.Code));

如果您不想要空值,您也可以将它们过滤掉:

bool isVal = lstCode.Any(c => !string.IsNullOrEmpty(c.HaveVal) 
                                 && lstStuff.Any(s => s == c.Code)); 

Here's a demo