这是我的应用程序中当前的代码,使用匿名委托来搜索属性集合:
public class MyObject
{
public MyObject() { }
public string MyObjectId { get; set; }
public List<MySubObject> SubObjects { get; set; }
}
public class MySubObject
{
public MySubObject() { }
public string MySubObjectId { get; set; }
}
public List<MyObject> Search(string input)
{
List<MyObject> AllObjects = Data.GetAllObjects();
List<MyObject> SearchResults = new List<MyObject>();
SearchResults = AllObjects.FindAll
(
delegate(MyObject o)
{
return e.MyObjectId.Equals(input)
}
);
if (SearchResults .Count.Equals(0))
SearchResults = null;
return SearchResults ;
}
我想修改匿名委托以通过通用列表中的
MySubObject.MySubObjectId
属性而不是MyObjectId
属性进行搜索。我将如何修改匿名委托中的代码以实现此目的? 最佳答案
尝试以下
delegate(MyObject o) {
var mySubObject = o as MySubObject;
return mySubObject != null && mySubObject.MySubObjectId == input;
}
请注意,您也可以在此处使用较短的lambda语法
(o) => {
var mySubObject = o as MySubObject;
return mySubObject != null && mySubObject.MySubObjectId == input;
}
或LINQ查询
var searchResult = AllObjects
.OfType<MySubObject>()
.Where(x => x.MySubObjectId == input)
.Cast<MyObject>()
.ToList()