如何存储From-To值并生成数组

时间:2014-05-20 07:33:16

标签: c# range containers

我想在数组中存储一些带有“fromValue”,“ToValue”,“Info”字段的项目,并编写一个例程来搜索“FromValue”和&之间的输入“值”。 “ToValue”并返回“Info”字段。我需要快速搜索容器。

FromValue,ToValue,Info   
10,20,TX   
24,56,NY   
input =34 returns NY

由于

3 个答案:

答案 0 :(得分:1)

好的,这个类定义了你的通用范围。

public class Range<TValue, TInfo>
{
    private readonly IComparer<TValue> comparer;

    public Range(IComparer<TValue> comparer)
    {
        this.comparer = comparer;
    }

    public Range(IComparer<TValue> comparer)
        : this(Comparer<TValue>.Default)
    {
    }

    public TValue From { get; set; }
    public TValue To { get; set; }
    public TInfo Info { get; set; }

    public bool InRange(T value, bool inclusive = true)
    {
        var lowerBound = this.comparer.Compare(value, this.From);
        if (lowerBound < 0)
        {
            return false;
        }
        else if (!inclusive && lowerBound == 0)
        {
            return false;
        }

        var upperBound = this.comparer.Compare(value, this.To);
        if (upperBound > 0)
        {
            return false;
        }
        else if (!inclusive && upperBound == 0)
        {
            return false;
        }

        return true;
    }
}

所以,你可以有一系列范围,

IEnumerable<Range<int, string>> ranges = ...

要查找范围内的所有信息值,

var rangesInRange = ranges.Where(r => r.InRange(42)).Select(r => r.Info);

您可以制作专门的容器来改善此操作。

答案 1 :(得分:0)

这很简单。 在最简单的场景中,只需创建一个类Item

public class Item
{
    public int Id { get; set; }
    public int FromValue { get; set; }
    public int ToValue { get; set; }
    public string Info { get; set; }
}

通过此功能,您可以初始化类型List<T>

的集合
List<Item> Items = new List<Item>()
{
    new Item() {Id = 1, FromValue = 10, ToValue = 20, Info = "TX"}
    new Item() {Id = 2, FromValue = 24, ToValue = 56, Info = "NY"}
    new Item() {Id = 3, FromValue = 15, ToValue = 34, Info = "FL"}
};

通过这个,你可以查询它的内容。

var itemsFromFlorida = Items.Where(it => it.Info == "FL");

答案 2 :(得分:0)

<强>类别:

public class Information
        {
            public int FromValue { get; set; }
            public int ToValue { get; set; }
            public string Info { get; set; }
        }

搜索

   List<Information> Informations = new List<Information>();
    Information infoObj = new Information();
    infoObj.FromValue = 10;
    infoObj.ToValue = 20;
    infoObj.Info = "TX";
    Informations.Add(infoObj);
    Information infoObj2 = new Information();
    infoObj2.FromValue = 24;
    infoObj2.ToValue = 56;
    infoObj2.Info = "NY";
    Informations.Add(infoObj);
    //passing sample input which lies between fromvalue and tovalue
    int sampleInput = 15;
    var result = Informations.FirstOrDefault(x => x.FromValue < sampleInput && sampleInput < x.ToValue);