繁体   English   中英

使用 C# 中的 LINQ 从列表中确定较低值

[英]Determine lower value from a list using LINQ in C#

我有一个包含四个双精度值的列表

var numbers2 = new List<double>() { 2, 3, 9, 7 };

我需要在前 2 个索引(2 和 3)之间获得较低的值。 同样,我需要在索引 3 和 4(9 和 7)之间获得较低的值

C 有没有办法使用 LINQ 来确定这个? 一旦我从上面的列表中得到较低的值,即 2 和 7; 我需要在下面的循环中传递这些值

for (int i = 0; i < 1; i++)
{
    dac[i] = SetValue(lowerValue[j]); 
}

如果i == 0 ,我想要lowerValue[j] = 2 如果i == 1 ,我想要lowerValue[j] = 7

正如其他人指出的那样,似乎没有任何理由使用 linq。 但是,如果您绝对必须找到某种方法来做到这一点,那么这是可能的。 我将抛出 3 个选项,最后一个是 linq。

using System;
using System.Linq;
using System.Collections.Generic;
        
public class Program
{
    public static void Main()
    {
        var numbers2 = new List<double>() { 2, 3, 9, 7 };
        
        // you stated it's always 4 values.  There's no reason to use linq. The optimal solution would 
        // be a variation of this (with some constant values instead of magic numbers)..
        
        var first = Math.Min(numbers2[0],numbers2[1]);
        var second = Math.Min(numbers2[2],numbers2[3]);
        
        Console.WriteLine($"Lower values: {first},{second}");
        
        // if it was an arbitry sized list (but always even count) you could use a iterator method
        var listOfLowerValues = ToPairs(numbers2);
        
        var values = string.Join(",", listOfLowerValues.Select(x => x.ToString()));
        
        Console.WriteLine($"Lower values: {values}");
        
        // finally if you absolutely had too, you can make it even more inefficient
        // by using linq.
        
        var indexes = Enumerable.Range(0, numbers2.Count);
        var indexed = numbers2.Zip(indexes, (n,i) => (index: i, num: n));
        var odd = indexed.Where(x => x.index%2 == 0).Select(x => x.num).ToArray();
        var even = indexed.Where(x => x.index%2 > 0).Select(x => x.num).ToArray();
            
        var lower = even.Zip(odd,(v1,v2)=> v1 < v2 ? v1 : v2);
        
        var valuesByLinq = string.Join(",",lower.Select(x => x.ToString()));
        
        Console.WriteLine($"Lower values: {valuesByLinq}");
    }
    
    static IEnumerable<double> ToPairs(IEnumerable<double> source)
    {
        int index = 0;
        double previous = 0;
        foreach(var n in source)
        {
            if(index++%2 > 0)
            {
                yield return (previous < n) ? previous : n;
            }
            else
            {
                previous = n;
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM