如果您有一个List,如果存在指定的属性或属性集,如何返回该项?
public class Testing
{
public string value1 { get; set; }
public string value2 { get; set; }
public int value3 { get; set; }
}
public class TestingList
{
public void TestingNewList()
{
var testList = new List<Testing>
{
new Testing {value1 = "Value1 - 1", value2 = "Value2 - 1", value3 = 3},
new Testing {value1 = "Value1 - 2", value2 = "Value2 - 2", value3 = 2},
new Testing {value1 = "Value1 - 3", value2 = "Value2 - 3", value3 = 3},
new Testing {value1 = "Value1 - 4", value2 = "Value2 - 4", value3 = 4},
new Testing {value1 = "Value1 - 5", value2 = "Value2 - 5", value3 = 5},
new Testing {value1 = "Value1 - 6", value2 = "Value2 - 6", value3 = 6},
new Testing {value1 = "Value1 - 7", value2 = "Value2 - 7", value3 = 7}
};
//use testList.Contains to see if value3 = 3
//use testList.Contains to see if value3 = 2 and value1 = "Value1 - 2"
}
}
Run Code Online (Sandbox Code Playgroud)
Cub*_*anX 23
如果您使用的是.NET 3.5或更高版本,LINQ就是这个问题的答案:
testList.Where(t => t.value3 == 3);
testList.Where(t => t.value3 == 2 && t.value1 == "Value1 - 2");
Run Code Online (Sandbox Code Playgroud)
如果不使用.NET 3.5,那么你可以循环选择你想要的那些.
如果要使用类的相等实现,可以使用该Contains方法.根据您如何定义相等性(默认情况下它将是参考,这将不是任何帮助),您可以运行其中一个测试.您还可以为IEqualityComparer<T>要执行的每个测试创建多个s.
或者,对于不依赖于类的相等性的测试,您可以使用该Exists方法并传入委托进行测试(或者Find如果您想要对匹配实例的引用).
例如,您可以在Testing类中定义相等,如下所示:
public class Testing: IEquatable<Testing>
{
// getters, setters, other code
...
public bool Equals(Testing other)
{
return other != null && other.value3 == this.value3;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您将使用以下代码测试列表是否包含value3 == 3的项目:
Testing testValue = new Testing();
testValue.value3 = 3;
return testList.Contains(testValue);
Run Code Online (Sandbox Code Playgroud)
要使用Exists,您可以执行以下操作(首先使用委托,第二个使用lambda):
return testList.Exists(delegate(testValue) { return testValue.value3 == 3 });
return testList.Exists(testValue => testValue.value3 == 2 && testValue.value1 == "Value1 - 2");
Run Code Online (Sandbox Code Playgroud)