Tutorial :C# if statement syntax with list of objects



Question:

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.


Solution:1

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.


Solution:2

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


Solution:3

Without LINQ!:

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


Solution:4

You can use LINQ to objects

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


Solution:5

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);    }  


Solution:6

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.


Solution:7

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...  }  


Solution:8

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
Previous
Next Post »