I want to compare a property instead of the entire object using a List[MyObject]. I therefore use IEquatable[MyObject] but the compiler still wants MyObject instead of the string property. Why?
Here is what I got:
public class AnyClass
{
public List<AnyOtherClass> MyProperty { get; set; }
public string AnyProperty { get; set; }
public AnyClass(string[] Names, string[] Values, string AnyProperty)
{
this.AnyProperty = AnyProperty;
this.MyProperty = new List<AnyOtherClass>();
for (int i = 0; i < Names.Length; i++)
MyProperty.Add(new AnyOtherClass(Names[i], Values[i]));
}
}
public class AnyOtherClass : IEquatable<string>
{
public AnyOtherClass(string Name, string Values)
{
this.Name = Name;
this.Values = Values.Split(';').ToList();
}
public string Name { get; set; }
public List<string> Values { get; set; }
public bool Equals(string other)
{
return this.Name.Equals(other);
}
}
private void DoSomething()
{
string[] Names = new string[] { "Name1", "Name2" };
string[] Values = new string[] { "Value1_1;Value1_2", "Value2" };
AnyClass ac = new AnyClass(Names, Values, "any Property");
if (ac.MyProperty.Contains("Name1")) //Problem is here...
//do something
}
Contains(T) Method is used to check whether an element is in the List<T> or not.
In C#, String. Contains() is a string method. This method is used to check whether the substring occurs within a given string or not. It returns the boolean value.
Contains: This method determines equality by using the default equality comparer, as defined by the object's implementation of the IEquatable(Of T). Equals method for T (the type of values in the list). This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.
You might want to try using this :
myList.Any(x => x.someProperty == someValue);
from MSDN : http://msdn.microsoft.com/en-us/library/bb534972.aspx
Determines whether any element of a sequence satisfies a condition.
The x => x.someProperty == someValue
is called a lambda expression
in case you didn't know.
And note that you can use this on anything implementing IEnumerable
, so that doesn't restrict you to List<T>
.
sounds like you should be doing a Where
rather than a Contains
string value = "test";
ac.Where(ac => ac.Name1 == value || ac.Name2 == value);
The reason ac.MyProperty.Contains("Name1")
is blowing up is because MyProperty
is a List<AnyOtherClass>
and not a string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With