Home > database >  Check if List with multiple Columns contains string
Check if List with multiple Columns contains string

Time:04-21

How do i check if the first column of my list RequirementList contains a string / element

 public class RequirementList
  {
    public string? Name{ get; set; }
    public string? Value { get; set; }
  }

Check here:

var requirementList = new List<RequirementList>();
//requirementList is already filled

  if(requirementList.Name.Contains("Test"))
{
     //do something
}

CodePudding user response:

Considering that Name can be null here, you should do it like this:

if(requirementList.Any(x=>x.Name is not null && x.Name.Contains("Test"))

Note that Contains here will be case sensitive. You can check this answer to handle case insensitivity Case insensitive 'Contains(string)'

CodePudding user response:

to complete or give another flavor with a modern c# you can write this as

if(requirementList.Any(x=>x?.Name.Contains("Test") ?? false)

CodePudding user response:

You seem to have some misconceptions around lists and properties, so I'll try to make it a little more clear. Some of this has been mentioned by others.

First, don't call something list, if it isn't a list. RequirementList should be called RequirementItem or just Requirement.

Now your definition looks like this:

var requirementList = new List<Requirement>();

See, it's already more logical.

Second, Name and Value are properties of a Requirement, they are not columns and you shouldn't think of them as such. Hence first doesn't apply, there is no first property

public class Requirement
{
    public string? Name{ get; set; }
    public string? Value { get; set; }
}

is equivalent to

public class Requirement
{
    public string? Value { get; set; }
    public string? Name{ get; set; }
}

And finally it looks like you want do something special to requirements with test in the name, so you should select the requirements first:

var requirementList = new List<Requirement>();
...
var testRequirements = requirementList.Select(x=>x?.Name.Contains("Test"));
if (testRequirements.Any())
{
    foreach (var req in testRequirements)
    {
        // do something with req
    }
}

This saves you the trouble of doing Any first and then select the ones you need to work with.

  • Related