c# - 如何替换一组 int 值?

标签 c# arrays algorithm entity-framework linq

我有一个数据库,表中有 60 个值,这些值每分钟自动填充一次。我有一个查询,第一次将获取这 60 个值并填充 int 数组。

然而,此方法每分钟都会使用 SignalR 执行一次,逻辑应该是数组的位置 0 应替换为位置 1,位置 1 替换为 2,依此类推,最后一个 (59!) 必须填充使用数据库中的最后一个值。

我不想每分钟重新创建数组,更不想对每次返回 60 行的数据库进行选择。

我的代码如下

public class Chart_Broadcaster
{
    //The Line Chart Class    
    public class LineChart
    {
        [JsonProperty("lineChartData")]
        private int[] lineChartData;
        [JsonProperty("colorString")]
        private string colorString;

        [JsonProperty("hora")]
        private string[] hora = new string[60];

        public void SetLineChartData()
        {               
            //Suppose we have a list of 60 items.
            using (ZigBeeContext db = new ZigBeeContext())
            {
                var lista = (from p in db.Medidas orderby p.FechaHora descending
                                    select p                             
                             ).Take(60).ToList();

                lineChartData = db.Medidas.Select(p => p.Temperatura).Cast<int>().ToArray();
                hora = db.Medidas.Select(p => p.FechaHora).Cast<string>().ToArray();

            }
        }
    }
}

最佳答案

一个不错的方法是使用队列而不是数组。来自 MSDN docs :

Represents a first-in, first-out collection of objects

这意味着您只需要 push新项目到队列的 bacl 和 pop旧的从前面掉下来。无需担心每次都将元素放置在一个位置并将其洗牌,因为这一切都会为您处理。

因此,当您需要添加新值时,只需执行以下操作:

//For example (you can't do this but it demonstrates the contents of the queue
var queue = new Queue<int> { 1, 2, 3, 4, 5 } 

var newInt = 6;
queue.Enqueue(newInt);
var oldInt = queue.Dequeue(); //Or don't even bother storing it if you don't want it

另一个时髦的方法是使用 .Net 的响应式扩展 ( )。这与 SignalR 作为排队系统配合得很好。

关于c# - 如何替换一组 int 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39147571/

相关文章:

c# - 从 .NET HashSet 按索引选择元素

C# - 查找输出

java - 尝试在 Java 中搜索 JSON

用于树结构的类似 Python numpy 的接口(interface)

c - 字符串段错误问题

algorithm - 数据结构。 f(x) 和 g(x)

c# - 使用映射从点集合中删除重复项

c# - 如何获取isPersistent(AuthenticationProperties)

algorithm - 在序列数组中找到最匹配的数字序列

sql - 根据轴坐标查询 "surrounding hex tiles"