我可以通过扩展方法来解构容器:
var limits = new[] { MyEnum.A , MyEnum.B , MyEnum.C }
.ToDictionary( x => x ,
x => ( SupportedLimit: GetLimit( x ) , RequiredLimit: 0 ) );
public static class Extensions
{
public static void Deconstruct<TKey, TVal>(
this KeyValuePair<TKey , TVal> tuple ,
out TKey key , out TVal value )
{
key = tuple.Key;
value = tuple.Value;
}
public static void Deconstruct<TKey, TVal1, TVal2>(
this KeyValuePair<TKey , (TVal1,TVal2)> tuple ,
out TKey key , out TVal1 v1 , out TVal2 v2 )
{
key = tuple.Key;
(v1 , v2) = tuple.Value;
}
}
// works
foreach( var ( enumVal , supportedLimit , requiredLimit ) in limits )
Debugger.Break();
如何在LINQ中解构包含System.ValueTuple
的容器/词典?
// won't work, .Where() expects Func<T,bool> not Func<T1,T2,T3,bool>
var failedLimits = limits.Where( ( _ , sup , req ) => sup < req );
我只是想知道如何(以及是否)可以在(任何)LINQ方法中解构ValueTuple。我想我必须为每个Linq方法(类似于列表的方法)添加扩展方法+字典的重载+ ValueTuple中的每个值数量。 示例中的Where()看起来如何?
答案 0 :(得分:1)
public static class LinqExtensions
{
public static IEnumerable<KeyValuePair<TKey,(T1,T2)>> Where<TKey,T1,T2>(
this IEnumerable<KeyValuePair<TKey,(T1,T2)>> source ,
Func<TKey,T1,T2, Boolean> predicate )
=> source.Where( predicate );
}
答案 1 :(得分:0)
由于您正在处理Dictionary
,因此您迭代的值是KeyValuePair
。您需要处理Value
的{{1}}部分,然后才使用值元组的named属性。
KeyValuePair