我是 LINQ 的新手,我正在做一个简单的项目来学习该技术的特性。
目前我有一个静态类,它包装了一个对象数组(一种简单的工厂)。假设它看起来像下面这样:
public static class Factory
{
private static Item[] items = new Item[]
{
// items are created here
};
// ...
}
现在我可以向我的工厂添加一些函数,以允许我查询内部数组,例如
public static Item GetByID(ItemID id)
{
var query =
from item in items
where item.ID == id
select item;
return query.First();
}
但是,这需要我修改 Factory 类的内部结构。有没有办法从“外部世界”编写此类查询?
public class OtherClass
{
var result = from it in Factory select ...
}
?
最佳答案
是的,你可以。只需在“外部世界”的工厂上使用 linq:
public class OtherClass
{
public Item Get(ItemId id)
{
return Factory.Items.SingleOrDefault(i => i.ID == id);
}
}
当然,为此,您需要将 items
数组的访问修饰符更改为 public
。
关于c# - 将 LINQ 与包装数组一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21564562/