LINQ Return null even if it meets condtion

Not sure why it happen, I observed it in debugging mode and condition inside the LINQ has been meet

if (chkSometing.Checked)
{
  var _results = from itemlist in dtResult.AsEnumerable()
                 where itemlist.Field<string>("data_visibility").Contains("both")
                 select itemlist;
  try { dtResult = _results.CopyToDataTable(); }
  catch (Exception ex) { Response.Write(ex.Message); }
}

Upvotes: 0

Views: 81

Answers (1)

Gauravsa
Gauravsa

Reputation: 6514

Although you may have fixed the problem, I can explain why "Contains" didnt work and "Any" will work in this case.

Contains check if the sequence contains an element.

Any checks if any element of sequence satisfies a condition. Its like a predicate.

So, if you wish to check whether an element of a sequence satisfies a condition use "Any". Example below:

List<string> list = new List<string> { "a", "aa", "aaa", "b", "c" };

bool containsBoy = list.Contains("c"); //true
// list.ElementAt(0).Contains("c") // --> Error which is what you are getting

bool anyBoy = list.Any(r => r.Length == 2); // true for "aa"

Source: What is the difference between Contains and Any in LINQ?

Upvotes: 2

Related Questions