Reputation: 851
I have the following delegate function in a Unit Test, and it works great
List<Record> RecordSet = FileData.RecordSet;
Record result = RecordSet.Find(
delegate(Record r)
{
return r.UserID == "12345";
}
);
and it works great. I need to perform this search multiple times, so I had tried to add it in a function I could call that took the UserID as a parameter, it's VERY similar, but for some reason, ALWAYS returns null.
public Record findRecord(List<Record> RecordSet, string UserID)
{
Record result = RecordSet.Find(
delegate(Record r)
{
return r.UserID.Trim() == UserID;
}
);
return null;
}
I have also tried it by hard coding "12345" in as the UserID value, that also returns null. What's even stranger is that when I am in debug mode and I look at the values in the RecordSet, I do see the Record with the exact UserID. Yet for some reason, no results, yet the same code and the same data in the first function above returns a result just fine.
Also, FYI, I have fond the LINQ solution to the problem:
Record result = RecordSet.Where(x => x.UserID == "12345").Select(x => x).First();
But I am specifically looking for reasons why the delegate solution is failing
Upvotes: 2
Views: 116
Reputation: 148980
The problem is that your method always returns null
, because of this line:
return null;
Replace it with this and you should have better luck:
return result;
However, you can simplify this with a lambda expression which takes a Record
and returns a bool
. Try this:
return RecordSet.Find(r => r.UserID.Trim() == UserID);
Upvotes: 5