开发者

how to add an associative index to an array. c#

i have an array of custom objects. i'd like to be able to reference this array by a particular data member, for instance myArrary["Item1"]

"Item1" is actually the value stored in the Name property of this custom type and I can write a predicate to mark the appropriate array item. However I am unclear as to how to let the array know i'd like to use this predicate to find the array item.

I'd like to just use a dictionary or hashtable or NameValuePair for this array, and get around this whole problem but it's generated and it must remain as CustomObj[]开发者_开发百科. i'm also trying to avoid loading a dictionary from this array as it's going to happen many times and there could be many objects in it.

For clarification

myArray[5] = new CustomObj() // easy!
myArray["ItemName"] = new CustomObj(); // how to do this? 

Can the above be done? I'm really just looking for something similar to how DataRow.Columns["MyColumnName"] works

Thanks for the advice.


What you really want is an OrderedDictionary. The version that .NET provides in System.Collections.Specialized is not generic - however there is a generic version on CodeProject that you could use. Internally, this is really just a hashtable married to a list ... but it is exposed in a uniform manner.

If you really want to avoid using a dictionary - you're going to have to live with O(n) lookup performance for an item by key. In that case, stick with an array or list and just use the LINQ Where() method to lookup a value. You can use either First() or Single() depending on whether duplicate entries are expected.

var myArrayOfCustom = ...
var item = myArrayOfCustom.Where( x => x.Name = "yourSearchValue" ).First();

It's easy enough to wrap this functionality into a class so that external consumers are not burdened by this knowledge, and can use simple indexers to access the data. You could then add features like memoization if you expect the same values are going to be accessed frequently. In this way you could amortize the cost of building the underlying lookup dictionary over multiple accesses.


If you do not want to use "Dictionary", then you should create class "myArrary" with data mass storage functionality and add indexers of type "int" for index access and of type "string" for associative access.

public CustomObj this [string index]
{
    get
    {
        return data[searchIdxByName(index)];
    }
    set
    {
        data[searchIdxByName(index)] = value;
    }
}

First link in google for indexers is: http://www.csharphelp.com/2006/04/c-indexers/


you could use a dictionary for this, although it might not be the best solution in the world this is the first i came up with.

    Dictionary<string, int> d = new Dictionary<string, int>();
    d.Add("cat", 2);
    d.Add("dog", 1);
    d.Add("llama", 0);
    d.Add("iguana", -1);

the ints could be objects, what you like :)

http://dotnetperls.com/dictionary-keys


Perhaps OrderedDictionary is what you're looking for.


you can use HashTable ;

System.Collections.Hashtable o_Hash_Table = new Hashtable();
o_Hash_Table.Add("Key", "Value");


There is a class in the System.Collections namespace called Dictionary<K,V> that you should use.

var d = new Dictionary<string, MyObj>();
MyObj o = d["a string variable"];

Another way would be to code two methods/a property:

public MyObj this[string index]
{
    get
    {
        foreach (var o in My_Enumerable)
        {
            if (o.Name == index)
            {
                return o;
            }
        }
    }
    set
    {
        foreach (var o in My_Enumerable)
        {
            if (o.Name == index)
            {
                var i = My_Enumerable.IndexOf(0);
                My_Enumerable.Remove(0);
                My_Enumerable.Add(value);
            }
        }
    }
}

I hope it helps!


It depends on the collection, some collections allow accessing by name and some don't. Accessing with strings is only meaningful when the collection has data stored, the column collection identifies columns by their name, thus allowing you to select a column by its name. In a normal array this would not work because items are only identified by their index number.


My best recommendation, if you can't change it to use a dictionary, is to either use a Linq expression:

var item1 = myArray.Where(x => x.Name == "Item1").FirstOrDefault();

or, make an extension method that uses a linq expression:

public static class CustomObjExtensions
{
    public static CustomObj Get(this CustomObj[] Array, string Name)
    {
        Array.Where(x => x.Name == Name).FirstOrDefault();
    }
}

then in your app:

var item2 = myArray.Get("Item2");

Note however that performance wouldn't be as good as using a dictionary, since behind the scenes .NET will just loop through the list until it finds a match, so if your list isn't going to change frequently, then you could just make a Dictionary instead.


I have two ideas:

1) I'm not sure you're aware but you can copy dictionary objects to an array like so:

Dictionary dict = new Dictionary();
dict.Add("tesT",40);
int[] myints = new int[dict.Count];
dict.Values.CopyTo(myints, 0);

This might allow you to use a Dictionary for everything while still keeping the output as an array.

2) You could also actually create a DataTable programmatically if that's the exact functionality you want:

DataTable dt = new DataTable();
DataColumn dc1 = new DataColumn("ID", typeof(int));
DataColumn dc2 = new DataColumn("Name", typeof(string));
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
DataRow row = dt.NewRow();
row["ID"] = 100;
row["Name"] = "Test";
dt.Rows.Add(row);

You could also create this outside of the method so you don't have to make the table over again every time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜