2009-05-21 52 views
0

我需要在“表”中查找一个值,其中表可以是一个数组或任何真正的值。
在纸面上它看起来像这样(还原和广义):查找“表”中的值的有效方法C#

Size  500  750 1000 1250 1500 (speed) 
-------------------------------------------- 
6x5  0.1  0.5  0.55 0.58 0.8 
6x4  0.01 0.1  0.4 0.5 0.9 
8x5  0.5  0.9  1.1 1.5 2.0 
10x5  1.2  1.5  2.0 2.7 3.0 
12x6  2.6  3.0  4.4 5.1 7.0 (pressure) 

我需要以某种方式提取压力时,我有可变大小和速度。
我现在我已经把每一行放在一个单独的数组中,但我想避免一堆如果其他的,但我真的不知道更好的方法。谢谢您的帮助。

回答

4

假设你的规模和速度总是特定值和不要在你的例子指定的值(所以没有大小780598为例)之间的下降,执行基于速度和大小查找最快的方法是有一个Dictionary<SizeAndSpeed, double>其中SizeAndSpeed是一类这样的:

public class SizeAndSpeed : IEquatable<SizeAndSpeed> 
{ 
    public string Size { get; set; } 
    public int Speed { get; set; } 
    public bool Equals(SizeAndSpeed other) 
    { 
     return Size == other.Size && Speed == other.Speed; 
    } 
} 

我假设Size可以是string,但当然也可以使用更复杂的对象。

0

在我的头顶,你可以使用一个DataTable。

Size  Speed  Pressure 
-------------------------------------------- 
6x5  500  0.1 
6x5  750  0.5 
6x5  1000  0.55 
6x5  1250  0.58 
6x5  1500  0.8 
6x4  500  0.01 
1

如果大小是唯一的,使它的关键词典,然后你可以用它来获得其他元素...

0

创建一个结构来保持规模和速度对:

然后
public struct SizeSpeedKey 
{ 
public string Size; 
public int Speed; 

public SizeSpeedKey(string size, int speed) 
{ 
    Size = size; 
    Speed = speed; 
} 
} 

这将是查找代码:

using System; 
using System.Collections.Generic; 

namespace LookupTable 
{ 
    internal class Program 
    { 
    private static readonly Dictionary<SizeSpeedKey, double> lookupTable = 
     new Dictionary<SizeSpeedKey, double> 
     { 
     {new SizeSpeedKey("6x5", 500), 0.1}, 
     {new SizeSpeedKey("6x5", 750), 0.5}, 
     {new SizeSpeedKey("6x4", 500), 0.01}, 
     {new SizeSpeedKey("6x4", 750), 0.1}, 
     {new SizeSpeedKey("8x5", 500), 0.5}, 
     {new SizeSpeedKey("8x5", 750), 0.9}, 
     }; 

    private static void Main(string[] args) 
    { 
     // these will of course need to be read from the user 
     var size = "6x4"; 
     var speed = 500; 

     Console.WriteLine("For size = {0} and speed = {1}, the pressure will be {2}", size, speed, lookupTable[new SizeSpeedKey(size, speed)]); 
     Console.ReadLine(); 
    } 
    } 
} 
+0

这是行不通的。 SizeSpeedKey不实现IEquatable ,因此字典如何比较键值? – 2009-05-21 22:28:51

相关问题