Domanda

I have a List<ObjectA> populated. Class ObjectA has two properties -string property1 bool? property2

[1]I need to loop through the entire list to check if property1 contains a particular string say 'xyz'.

[2] I need to check if value of property2 is true(which i believe i can figure out after getting to know how to handle [1])

thanks Adarsh

È stato utile?

Soluzione

With List<T> you can also use its method TrueForAll:

bool valid = list.TrueForAll(a => a.property1.Contains("xyz") && a.property2);

This will work on any version of .NET >= 2.0. You also can use LINQ as @Hassan suggested:

bool valid = list.All(a => a.property1.Contains("xyz") && a.property2);

That will work on .NET >= 3.5. Benefit of this option is ability to work with any enumerable source (i.e. if you'll change list to ICollection, or some other enumerable type).

Altri suggerimenti

if you want to make sure if all elements of a particular collection satisfy a condition you can use All method in Linq, like this:

 new List<MyClass>().All(m => m.StringProp.Contains("ss") && m.IsValid == true)

Use LINQ:

List<ObjectA> list;

//Check for string
if (list.Any(a => a.property1.Contains("xyz")))
{

}

// Check for true
if (list.Any(a => a.property2 ?? false))
{

}

If you need to get the objects that satisfies your conditions, use list.Where(...)

There are several possible checks and results you can easily get.

void Main()
{       //ignore Dump() method
    var list = new List<ObjectA>() 
    {
        new ObjectA("name1", true),
        new ObjectA("name2", true),
        new ObjectA("name3", null),
        new ObjectA("name4", false),
        new ObjectA("name5", null),
        new ObjectA("name6", false),
        new ObjectA("name7", true)
    };
    //check if all Items are valid
var allItems = list.All(m => m.Name.Contains("ss") && m.valid == true); // false
    //only get valid items (name contains name AND true)
var validItems = list.Where (l => l.Name.Contains("name") && l.valid == true).Dump();
    //get all items which are invalid
var nonvalidItems = list.Where(l =>!(l.Name.Contains("name")) || l.valid != true).Dump();

}

public class ObjectA
{
  public ObjectA(string name, bool? _val)
  {
    this.Name = name;
    if(_val.HasValue)
      this.valid = _val;
  }
 public string Name { get; set; }
 public bool? valid { get; set; }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top