UNe*_*rNo 9 c# generics contains iequatable
我想使用List [MyObject]比较属性而不是整个对象.因此我使用IEquatable [MyObject],但编译器仍然需要MyObject而不是string属性.为什么?
这是我得到的:
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
}
Run Code Online (Sandbox Code Playgroud)
Pac*_*ane 21
您可能想尝试使用此:
myList.Any(x => x.someProperty == someValue);
Run Code Online (Sandbox Code Playgroud)
来自MSDN:http://msdn.microsoft.com/en-us/library/bb534972.aspx
确定序列的任何元素是否满足条件.
如果您不知道,x => x.someProperty == someValue
则称为a lambda expression
.
请注意,您可以在任何实现中使用它IEnumerable
,这样就不会限制您List<T>
.
归档时间: |
|
查看次数: |
14796 次 |
最近记录: |