【发布时间】:2010-10-12 10:58:30
【问题描述】:
我试图从一个字典保存的数组中获取一个可编号的集合。 或者我应该说,我正在尝试为我的字典对象编写一个扩展方法,该方法存储数组以在结果为空时返回一个 IEnumerable 项。
我使用字典来存储数组数据集(这有速度的原因),我在某些搜索点提取了这些数据集。提取的数据用于 Linq 查询、连接等,但是当数据集不存在时我会遇到问题。
返回一个空的(0 个计数)行集可以解决我的问题。到目前为止我所拥有的是这个(当然是简化的代码)
public class Supplier
{
public string ID {get;set}
public string Name {get;set}
}
private sups[] = new Supplier[10];
Dictionary<int,Supplier[]> dic = new Dictionary<int, Supplier[]>();
dic.Add(1,sups[]);
public static IEnumerable<Supplier> TryGetValue<Tkey>(this IDictionary<Tkey, Supplier[]> source, Tkey ItemKey)
{
Supplier[] foundList;
IEnumerable<Supplier> retVal;
if (source.TryGetValue(ItemKey, out foundList))
{
retVal = foundList.AsEnumerable();
}
else
{
retVal = new Supplier[0].AsEnumerable();
}
return retVal;
}
// 在后面的代码中有一些类似的东西:
dic.TryGetValue(1).Count()
//or a linq join
from a in anothertable
join d in dic.TryGetValue(1) on a.ID equals d.ID
我试图实现的是一个通用的扩展方法,如下所示:
public static IEnumerable<T> TryGetValue<Tkey,TValue>(this IDictionary<Tkey, TValue> source, Tkey ItemKey)
{
// same code...
// returning retVal = new T[0].AsEnumerable();
}
我不断接近,但从来没有完全在那里....我想保持扩展方法参数简单。是 T 的过世让我一直在抓狂。
如果有人可以提供帮助,请将您的反馈发回给我。
非常感谢!
【问题讨论】:
标签: c# generics dictionary ienumerable linq-to-objects