Let's say I have a List<string>
that looks like this:
var lstStuff = new List<String>(){"test", "value", "other"};
I also have a Model Class that looks like this
public class Codes {
public string Code {get;set;}
public string? HaveVal {get;set;}
}
In my C# method I have something like this. What I am trying to achieve is to return a TRUE
or FALSE
if any single item in lstStuff
has a HaveVal
in lstCode
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"}
};
}
Here's my code to achieve this, but I was wondering if there is a LINQ way of doing this.
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;
Is there a shorter way to do this, without needing to loop?
CodePudding user response:
You can use Any()
twice::
bool isVal = lstCode.Any(c => lstStuff.Any(s => s == c.Code));
If you don't want null values you can filter them out too:
bool isVal = lstCode.Any(c => !string.IsNullOrEmpty(c.HaveVal)
&& lstStuff.Any(s => s == c.Code));