gpt4 book ai didi

c# - Ienumerable 字典数组调用的扩展方法

转载 作者:太空宇宙 更新时间:2023-11-03 14:26:12 25 4
gpt4 key购买 nike

我正在尝试从字典保存的数组中获取可枚举的集合。或者我应该说,我正在尝试为我的字典对象编写一个扩展方法,它存储数组以在结果为 null 时返回一个 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 的逝去一直让我抓狂。

如果有人可以提供帮助,请将您的反馈发回给我。

非常感谢!

最佳答案

编辑:类型推断的并发症。

这是一种方法,其想法是将字典值的类型限制为某物IEnumerable

不幸的是,类型推断似乎不适用于此签名(使用 C# 3 测试),因此您必须明确指定通用参数。

public static IEnumerable<TUnderlyingValue> GetValueOrEmpty<TKey, TUnderlyingValue, TValue>
(this IDictionary<TKey, TValue> source, TKey key)
where TValue : IEnumerable<TUnderlyingValue>
{

if(source == null)
throw new ArgumentNullException("source");

TValue retVal;

return source.TryGetValue(key, out retVal) ? retVal : Enumerable.Empty<TUnderlyingValue>;
}

用法:

var dict = new Dictionary<string, int[]>
{
{ "foo", new[] { 6, 7, 8 } }
{ "bar", new[] { 1 } }
};

var fooOrEmpty = dict.GetValueOrEmpty<string, int, int[]>("foo"); // { 6, 7, 8 }
var barOrEmpty = dict.GetValueOrEmpty<string, int, int[]>("bar"); // { 1 }
var bazOrEmpty = dict.GetValueOrEmpty<string, int, int[]>("baz"); // { }

或者,我们可以只使用 2 个通用参数而没有任何限制,但这会降低字典类型的灵 active 。在这种情况下,编译器将很好地推断通用参数。

public static TUnderlyingValue[] GetValueOrEmpty<TKey, TUnderlyingValue>
(this IDictionary<TKey, TUnderlyingValue[]> source, TKey key)
{

if(source == null)
throw new ArgumentNullException("source");

TUnderlyingValue[] retVal;

return source.TryGetValue(key, out retVal) ? retVal : new TUnderlyingValue[0];
}

关于c# - Ienumerable 字典数组调用的扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3913907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com