Tutorial :C# if statement syntax with list of objects


I have a list of objects, called Attributes, that, essentially, i need to do the following in C#

<pseudocode>  if (list.Contains(Attribute where getName() == "owner"))  {     do stuff  }  </pseudocode>  

the problem I'm having is the nested bracket bit of the if - "Attribute where getName() == "owner". This is my code - it doesn't work, obviously, but most of the if should be right, it's just getting that i need to do the bit in forward slashes and i don't know how.

if (attributes.Contains(Attribute /where/ attribute.getName() == "Owner"))      {          string value = attr.getValue();          value = value.Replace(domain, "");          user = value;          UserExists(value);      }  

I'm probably being dense, but I had to restart 3 days development to change everything to using Attribute objects, so my brain is rather destroyed. Sorry.


If you are using a version of .NET that supports LINQ (3.5 or higher), try

if(attributes.Any(attribute=>attribute.getName()=="Owner"))  {      do stuff  }  

This has the nice advantage of being fairly readable by whoever has to maintain this code.


if(list.Exists(e=>e.getName() == "owner")) {     //yup  }  


Without LINQ!:

if (list.Exists(delegate(Attribute a) { return a.GetName() == "Owner"; }))  


You can use LINQ to objects

if (attributes.Count(a => a.getName() == "Owner") > 0)  


Please have a look:

var filteredAttributes = from attribute in Attributes                            where string.Compare(attribute.getName() ,"Owner",true)==0                           select attribute;    foreach(var attribute in filteredAttributes)  {            string value = attr.getValue();                  value = value.Replace(domain, "");                  user = value;                  UserExists(value);    }  


Ok, i worked it out, I found a much better way to do it:

for (int i = 0; i < attributes.Count; i++)  {      if (attributes[i].getName() == "Owner")      {         string value = attributes[i].getValue();         value = value.Replace(domain, "");         user = value;         UserExists(value);      }  }  

which makes more sense, and actually works.


You can use LINQ to separate out the required attributes...

IEnumerable<TAttribute> ownerAttributes =      attributes.Where(attribute => attribute.getName() == "Owner");  

... and then iterate over those attributes, applying the relevant logic...

foreach(TAttribute attribute in ownerAttributes)  {      // Do stuff...  }  


are you using .NET 3.5 or above, if so and presuming that 'attributes' is derived from IEnumerable, you could do the following :

if (attributes.Any(attrib=>attrib.GetName() == "Owner"))  {      //Do code here...  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »