Pepys
Pepys

Reputation: 991

In List<string>, how to use the Contains() method and check if value is empty

I have a List<string> and some saved values taken from a gridview. What I need is to use a few if statements in order to check if one of these values in the list are empty.

A simple for loop going through all the rows in the gridview and taking values from the right column:

for (int i = 0; i < GridView2.Rows.Count; i++)
{
            string tasks = GridView2.Rows[i].Cells[3].Text;
            datesList.Add(tasks); 
 }

Here is a very simple example of code I'm using to check if 2 is in the list:

if (datesList.Contains("2"))
{
    Label1.Text = "It contains it";
}
else
{
    Label1.Text = "No matches";    
} 

So does the list saves all values from the gridview no matter that some are empty?

Correct me if I'm wrong somewhere but it's really confusing now...

Upvotes: 2

Views: 6461

Answers (3)

Pranay Rana
Pranay Rana

Reputation: 176934

Make use of Any() instead of this.

datalist.Any(s => s.fieldname == "2")

Upvotes: 7

CBRRacer
CBRRacer

Reputation: 4659

So your list of items should contain all values even if they are "" so if you want a specific item then you can do something like this

datalist.FirstOrDefault(i => i.FieldName == "//insert Data here");

if you want all but the items with string.Empty then you can do something like this

datalist.RemoveAll(i => i.FieldName != "");

if you want the items within a certain range then try something like this.

datalist.Select(i => i.FieldName.Contains("//insert criteria here"));

Upvotes: 0

Emond
Emond

Reputation: 50682

if(datesList.Any(date => !String.IsNullOrEmpty(date)))
{
   //save
}

To collect the set/filled fields:

var setDates = datesList.Select(date => !String.IsNullOrEmpty(date));

Upvotes: 3

Related Questions