المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : SortedList, Key as element of Value



C# Programming
05-13-2009, 10:50 PM
Let's say that you have a SortedList with the Key as a string and the Value as a struct. Also, the string Key is one of the data elements in the struct. Example:

using System;
using System.Collections.Generic;

namespace SortedListStructure
{
public struct Product
{
public string model;
public string description;
public int weight;
public int height;
public int width;
public int length;
};

class Program
{
static void Main(string[] args)
{
SortedList sl = new SortedList();
Product test;
test.model = "1X-3PA2Q94";
test.description = "Tractor Motor Sensor";
test.weight = 3;
test.height = 3;
test.width = 3;
test.length = 3;

sl.Add(test.model, test);

string m = test.model;
if (sl.ContainsKey(m))
{
Console.WriteLine("Description: {0}, Weight: {1}", sl[m].description, sl[m].weight);
}
else
{
Console.WriteLine("{0} not found", m);
}

Console.ReadLine();
}
}
}
While this works, the model is stored twice (I think? Is it?), once for the Key and once as one of the elements of the Product Value. One way to eliminate this redundancy would be to leave model out of the Product struct, but assume that this is not preferable. What is the most efficient approach when the Key is part of the Value?