繁体   English   中英

Linq是否可以直接使用字典?

[英]Is it possible to Linq Directly to a Dictionary?

我有一个高速应用程序使用List内的自定义类(价格,数量,日期时间)。 我要么添加到列表中,如果找不到价格,要么使用订单数量和日期时间更新它,然后在列表上运行查询以按顺序数量一遍又一遍地提取前4个事件。 该代码在前半个小时运行良好,之后成千上万条记录陷入困境。 我想过尝试一本字典,因为索引,但无法弄清楚更新和Linq语句。

  1. Linq是否可以直接使用字典中的字段,例如使用自定义类或结构来提取前4个字符? 如果是这样,一个简短的例子就会很棒

  2. 从具有更新的订单数量和日期时间的TryGetValue执行后,我可以直接更新字典字段吗? 如果是这样,一个简短的例子就会很棒

  3. ...或者词典不是继续前进的方式,记住速度至关重要吗?

任何帮助表示赞赏。

List<PriceLevel> TrackPrice = new List<PriceLevel>();
        decimal loopLast=0;//sample only
        int loopLastQuantity=0;//sample only
        DateTime inputDateDT=DateTime.Now;//sample

        // Add or Update List
          var foundit = TrackPrice.FirstOrDefault(x => x.ProgramPrice == loopLast);
                        if (foundit != null)// Found existing record

                        {
                            foundit.ProgramQuantity += loopLastQuantity;
                            foundit.ProgramLastTime = inputDateDT;
                        }
                        else // Add a new record
                        {
                            TrackPrice.Add(new PriceLevel
                            {
                                ProgramPrice = loopLast,
                                ProgramQuantity = loopLastQuantity,
                                ProgramLastTime = inputDateDT,

                            });
                        }
                    }
    // Query the List
         var finalFourQuantities = (from a in TrackPrice
                                               orderby a.ProgramQuantity descending
                                               where a.ProgramQuantity > 300000
                                               select new
                                               {
                                                   a.ProgramPrice,
                                                   a.ProgramQuantity,
                                                   a.ProgramLastTime,
                                               }).Take(4);

                    foreach (var myprice in finalFourQuantities)
                    {   
                        //Process 4 order prices
                    }               

        public class PriceLevel
    {
        public decimal ProgramPrice         { get; set; }
        public int ProgramQuantity          { get; set; }
        public DateTime ProgramLastTime     { get; set; }// Last Order Time
    }

您可以简单地在字典的Values属性上运行linq查询,将其视为任何其他IEnumerable<T>

关于解决方案的性能,您可以尝试自己将4个当前最高值存储在一个数组中,然后每当添加/更新一个值时,您只需要将新值与当前最高值进行比较,如果是,则交换一个值。新价值更高。 这将消除对整个数据集的线性搜索的需要。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM