简化以下算法

时间:2013-11-18 08:47:54

标签: c# linq dictionary

我正在使用LINQ查询来检索存储在Dictionnary中的一定数量的KeyValuePair<string, string>(名为Prix,其中包含1到n KeyValuePair)。根据此查询的结果,我填写DataRow(在切换中)。DataRow中存储的最大价格为3,除非hasEAN为真,在这种情况下,最大值为2.如果我在Prix中只有1个价格,我只存储1个价格。 algorythm如下:

List<KeyValuePair<string, string>> prices;
if (this.Prix.Count > 1)
{
    if (this.Prix.Count >= 2)
    {
        if (this.hasEAN)
        {
            prices = (from kvp in this.Prix
                      select kvp).Take(2).ToList();
        }
        else
        {
            prices = (from kvp in this.Prix
                      select kvp).Take(3).ToList();
        }
    }
    else
    {
        prices = (from kvp in this.Prix
                  select kvp).Take(1).ToList();
    }
}
else
{
    prices = null;
}

switch (prices.Count)
{
    case 1:
        res[8] = prices[0].Key;
        res[9] = prices[0].Value;
        break;
    case 2:
        res[8] = prices[0].Key;
        res[9] = prices[0].Value;
        res[10] = prices[1].Key;
        res[11] = prices[1].Value;
        break;
    case 3:
        res[8] = prices[0].Key;
        res[9] = prices[0].Value;
        res[10] = prices[1].Key;
        res[11] = prices[1].Value;
        res[12] = prices[2].Key;
        res[13] = prices[2].Value;
        break;
    default:
        break;
}

我觉得它可能更简单但我不熟悉LINQ查询。

3 个答案:

答案 0 :(得分:2)

至少可以缩短代码的第一部分:

List<KeyValuePair<string, string>> prices = null;
if (Prix.Any())
{
    int count = Prix.Count == 1 ? 1 : hasEAN ? 2 : 3;
    prices = Prix.Take(count).ToList();
}

答案 1 :(得分:1)

List<KeyValuePair<string, string>> prices = this.Prix.Count <= 1 ? null : (from kvp in this.Prix select kvp).Take(this.Prix.Count < 2 ? 1 : this.hasEAN ? 2 : 3).ToList();

switch (prices.Count)
{
    case 3:
        res[12] = prices[2].Key;
        res[13] = prices[2].Value;
            goto case 2;
    case 2:
        res[10] = prices[1].Key;
        res[11] = prices[1].Value;
            goto case 1;
    case 1:
        res[8] = prices[0].Key;
        res[9] = prices[0].Value;
        break;
    default:
        break;
}

答案 2 :(得分:1)

这肯定可以与Linq一起使用,您可以从其他答案中看到,但不考虑未来的可维护性,如果您的规则发生变化以引入更多复杂性,您将来会做些什么? 您可以简化为仅定义一次查询:

List<KeyValuePair<string, string>> prices;
//we'll always want at least one
int numberToTake=1;
//if we have more than one price though
if (this.Prix.Count>1)
{
  //check if we have more than 2
   if (this.Prix.Count >= 2)
   {
   //and if we have an EAN, take only 2 prices
    if (this.hasEAN)
    {
        numberToTake=2;
    }
    else
    {
     //if no EAN, take 3 prices.
      numberToTake=3;
    }
  }
}
prices = (from kvp in this.Prix select kvp).Take(numberToTake).ToList();
switch (prices.Count)
{
 //...your switch here.
}

并且为了获得最佳效果,请将其转换为您的业务规则中的函数(无论this是什么)返回numberToTake,但如果您只想压缩到单行只是因为它看起来更好,我会敦促你重新考虑。