Reputation: 732
If you have a List how do you return the item if a specified property or collection of properties exists?
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"
}
}
Upvotes: 14
Views: 47060
Reputation: 4508
A LINQ query would probably be the easiest way to code this.
Testing result = (from t in testList where t.value3 == 3 select t).FirstOrDefault();
Upvotes: 1
Reputation: 5252
If you're using .NET 3.5 or better, LINQ is the answer to this one:
testList.Where(t => t.value3 == 3);
testList.Where(t => t.value3 == 2 && t.value1 == "Value1 - 2");
If not using .NET 3.5 then you can just loop through and pick out the ones you want.
Upvotes: 23
Reputation: 155925
If you want to use the class's implementation of equality, you can use the Contains
method. Depending on how you define equality (by default it'll be referential, which won't be any help), you may be able to run one of those tests. You could also create multiple IEqualityComparer<T>
s for each test you want to perform.
Alternatively, for tests that don't rely just on the class's equality, you can use the Exists
method and pass in a delegate to test against (or Find
if you want a reference to the matching instance).
For example, you could define equality in the Testing
class like so:
public class Testing: IEquatable<Testing>
{
// getters, setters, other code
...
public bool Equals(Testing other)
{
return other != null && other.value3 == this.value3;
}
}
Then you would test if the list contains an item with value3 == 3 with this code:
Testing testValue = new Testing();
testValue.value3 = 3;
return testList.Contains(testValue);
To use Exists, you could do the following (first with delegate, second with lambda):
return testList.Exists(delegate(testValue) { return testValue.value3 == 3 });
return testList.Exists(testValue => testValue.value3 == 2 && testValue.value1 == "Value1 - 2");
Upvotes: 8