Is it more suitable for storing key values ​​or a tree?

I am trying to find a better way to present some data. It basically follows the Manufacturer.Product.Attribute = Value form. Sort of:

Acme *. MinimumPrice = 100
Acme.ProductA.MinimumPrice = 50
Acme.ProductB.MinimumPrice = 60
Acme.ProductC.DefaultColor = blue

Thus, the minimum price for all Acme products is 100, with the exception of products A and B. I want to store this data in C # and have some function where GetValue ("Acme.ProductC.MinimumPrice") returns 100, but GetValue (" Acme.ProductA.MinimumPrice ") returns 50.

I'm not sure how best to present the data. Is there any way to do this in C #?

Edit: Perhaps I was not clean. These are configuration data that must be saved in a text file, then analyzed and stored in memory so that they can be obtained, as in the examples below.

+3
source share
4 answers

Write the text file exactly like this:

Acme.*.MinimumPrice = 100
Acme.ProductA.MinimumPrice = 50
Acme.ProductB.MinimumPrice = 60
Acme.ProductC.DefaultColor = Blue

Divide it into a sequence of pairs / path:

foreach (var pair in File.ReadAllLines(configFileName)
                         .Select(l => l.Split('='))
                         .Select(a => new { Path = a[0], Value = a[1] }))
{
    // do something with each pair.Path and pair.Value
}

Now there are two possible interpretations of what you want to do. A string Acme.*.MinimumPricecan mean that for any search where there is no specific redefinition, for example Acme.Toadstool.MinimumPrice, we return 100- even if there is nothing in the file that refers to Toadstool. Or it may mean that it should return 100if there are other specific references in the file Toadstool.

, , , -, .

, , , , . .

, , Acme.*.MinimumPrice " MinimumPrice , ". , , , :

Acme.ProductA.MinimumPrice = 50
Acme.ProductB.MinimumPrice = 60
Acme.ProductC.DefaultColor = Blue
Acme.ProductC.MinimumPrice = 100

, , TryGetValue [], . , .

, - , , API, , . ( ), .

+2

, , , .

, 100 , : ProductA ProductB

.

int GetValue(string key) { 
  if ( key == "Acme.ProductA.MinimumPrice" ) { return 50; }
  else if (key == "Acme.ProductB.MinimumPrice") { return 60; }
  else { return 100; }
}

, , , 100,

Dictionary<string,int>.

class DataBucket {
  private Dictionary<string,int> _priceMap = new Dictionary<string,int>();
  public DataBucket() {
    _priceMap["Acme.ProductA.MinimumPrice"] = 50;
    _priceMap["Acme.ProductB.MinimumPrice"] = 60;
  }   
  public int GetValue(string key) { 
    int price = 0;
    if ( !_priceMap.TryGetValue(key, out price)) {
      price = 100;
    }
    return price;
  }
}
0

- : Dictionary<string, Dictionary<string, Dictionary<string, object>>>. "Acme.ProductA.MinimumPrice" , .

Linq2Xml: XDocument Acme root node, , . , , .

0

. , , - , , . .

ProductBase, ,

virtual MinimumPrice { get { return 100; } }

, ProductA, :

override MinimumPrice { get { return 50; } }
0

Source: https://habr.com/ru/post/1737472/


All Articles