数组/列表管理问题c#,总noob

时间:2016-07-10 08:15:08

标签: c# arrays arraylist

对于c#,我是一个完全的菜鸟 我迁移到一个使用c#的新平台,尝试将交易规则迁移到新设计。 我需要为算法

执行此操作

这是问题所在 我有键阵列a,b,c,d 我有值set1 3,8,9,10 另一个值set2 77,89,100,76

这些值彼此相关,(a)具有值3,77等等

我需要的是,我需要使用值集2进行过滤,例如只有超过80的值(可能会创建一个包含剩余行的新列表),从剩余的列表中我需要获取具有最高set1的键名值

我用这可能非常糟糕的方式尝试了,

Array.Sort在一维数组值set1上,取值[3] - 如果这等于3那么(如果值set1> 80值,则其他值取值[2]并重复

你能告诉我一个更简单的方法,请考虑我的经验,并尽可能多地提供信息和代码

2 个答案:

答案 0 :(得分:1)

你应该开始更多地了解Linq。 C#具有非常强大的功能类特性,您可以轻松地完成这些操作。这真的很有趣:))

基本上,这个代码用3行做你想要的。

 var set1 = new[] {3, 8, 9, 10};
        var set2 = new[] {77, 89, 100, 76};

        var maxFromSet1 = set1
            .Zip(set2, (fromSet1, fromSet2) => new {FromSet1 = fromSet1, FromSet2 = fromSet2}) //Match the sets to one another
            .Where(zipped => zipped.FromSet2 > 80) // Filter by value
            .Max(zipped => zipped.FromSet1); //Gets max

答案 1 :(得分:0)

另一种做你想做的事情的方法是使用一个Dictionary来保存键和值,而不是将它们放在不同的数组中。

Dictionary<string, int[]> dic = new Dictionary<string, int[]>()
{
    { "a", new[] { 3, 77 } },
    { "b", new[] { 8, 89 } },
    { "c", new[] { 9, 100 } },
    { "d", new[] { 10, 76 } }
};

然后使用LINQ,您可以非常轻松地检索密钥

string key = dic.Where(x => x.Value[1] > 80) // Filter by second value
                .OrderByDescending(x => x.Value[0]) // Order by first value
                .First() // Get the max value
                .Key; // Get the matching key