.Net中是否有一种方法可以在运行LINQ表达式时动态调用ToDictionary(<lambda key>, <lambda val>)以减少返回Dictionary的样板。
C#示例:
Dictionary<string, object> d_filt;
Dictionary<string, object> d_in = new Dictionary<string, object>();
d_in.Add("k1", 4);
d_in.Add("k2", 3);
d_in.Add("k3", 2);
d_in.Add("k4", 1);
// Current Expression:
d_filt = d_in.Where(p => p.value > 2)
.ToDictionary(p => p.Key, p => p.Value);
// Preferred Expression:
d_filt = linq2Dict(d_in.Where(p => p.value > 2));其中,linq2Dict(<LinqObj>)是一个将动态调用ToDictionary(..)方法的助手。
我尝试过反射库,但是我熟悉的标准反射库似乎无法使用ToDictionary。
注意: VB更冗长:
Dim d_filt = d_in.Where(Function(p) p.value > 2).ToDictionary(Function(p) p.Key, Function(p) p.Value)当然,最巧妙的解决方案是添加一个不带任何参数的ToDict() Extension:
// Preferred Expression:
d_filt = d_in.Where(p => p.value > 2).ToDict()发布于 2022-06-20 18:14:59
不需要反射,只是普通的
public static class Convert
{
public static Dictionary<T,U> ToDict<T,U>(this IEnumerable<KeyValuePair<T,U>> source) where T : notnull
{
return source.ToDictionary(s=>s.Key,s=>s.Value);
}
}T的约束是因为Dictionary不能使用空键。
更重要的是,它维护了流畅的语法,因此您可以只使用
d_filt = d_in.Where(p => p.value > 2).ToDict();发布于 2022-06-20 18:47:51
为了在@Martheen's answer上构建,下面是如何在VB中实现ToDict()扩展:
Imports System.Runtime.CompilerServices
Module Convert
<Extension()>
Function ToDict(Of T, U)(ByVal source As IEnumerable(Of KeyValuePair(Of T, U))) As Dictionary(Of T, U)
Return source.ToDictionary(Function(s) s.Key, Function(s) s.Value)
End Function
End Module发布于 2022-06-20 18:58:26
以下是VB中linq2Dict()的一个实现:
Public Shared Function linq2Dict(Of T, U)(ByVal source As IEnumerable(Of KeyValuePair(Of T, U))) As Dictionary(Of T, U)
Return source.ToDictionary(Function(s) s.Key, Function(s) s.Value)
End Function例:
d_filt = linq2Dict(d_in.Where(p => p.value > 2))https://stackoverflow.com/questions/72691163
复制相似问题