我可以通过扩展方法来解构容器:

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()看起来如何?

最佳答案

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 );
}



类列表类型的重载+每个ValueTuple-parameter参数

关于c# - 在LINQ中解构包含ValueTuple的容器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52223591/

10-10 12:36