Reputation: 255
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.
Upvotes: 6
Views: 14679
Reputation: 20297
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.
Upvotes: 14
Reputation: 16018
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...
}
Upvotes: 0
Reputation: 10377
Without LINQ!:
if (list.Exists(delegate(Attribute a) { return a.GetName() == "Owner"; }))
Upvotes: 2
Reputation: 1028
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...
}
Upvotes: 0
Reputation: 255
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.
Upvotes: -1
Reputation: 11591
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);
}
Upvotes: 0
Reputation: 6859
You can use LINQ to objects
if (attributes.Count(a => a.getName() == "Owner") > 0)
Upvotes: 2