使用 linq 连接两个表,并填充它们的字典

Join two tables using linq, and fill a Dictionary of them(使用 linq 连接两个表,并填充它们的字典)
本文介绍了使用 linq 连接两个表,并填充它们的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我一直在寻找如何连接两个表(Data 和 DataValues,一对多)并填充类型为 的字典.

I've been searching how to join two tables (Data and DataValues, one to many) and fill a dictionary of type .

Data(s) 的记录可能是数千(例如 500,000 或更多),并且每个 Data 可能有 10 到 20 个 DataValues,这使得它的查询量更大,因此性能在这里非常重要.

The records of Data(s) might be thousands (e.g. 500,000 or more) and each Data may have 10 to 20 DataValues which makes it a much heavier query, so the performance is really important here.

这是我写的代码:

// Passed via the arguments, for example, sensorIDs would contain:
int[] sensorIDs = { 0, 1, 2, 3, 4, 5, 6, 17, 18 };
Dictionary<Data, List<DataValue>> dict = new Dictionary<Data, List<DataValue>>();

foreach (Data Data in dt.Datas)
{
    var dValues = from d in dt.Datas
                        join dV in dt.DataValues on d.DataID equals dV.DataID
                        where (SensorIDs.Contains(dV.SensorID))
                        select dV;
    dict.Add(Data, dValues.ToList<DataValue>());
}

但是这种方法存在严重的性能问题并且需要很长时间才能执行.不确定是否需要使用 SQL 视图.有什么建议吗?

But this approach has a significant performance issue and takes a long time to execute. Not sure if I need to use SQL Views. any suggestions?

推荐答案

您查询的次数太多了.您可以在一个查询中完成此操作.

You're querying way too many times. You can do this in one query.

var dict = (from d in dt.Datas
            join dV in dt.DataValues on d.DataID equals dv.DataID
            where SensorIDs.Contains(dv.SensorID)
            select new { d, dV }).ToDictionary(o => o.d, o => o.dV.ToList());

在您的 foreach 循环中,您正在获取所有 Data 并且对于它们中的每一个,您都在做同样的事情.

In your foreach loop, you are fetching all Data and for each of them, you are doing the same thing.

现在还不是很清楚,但我认为您只想加入 SensorIDs 数组中的 DataValues.在这种情况下:

Now that wasn't very clear, but I think you want to join only the DataValues that are in the SensorIDs array. In this case:

var dict = (from d in dt.Datas
            let dV = (from dataValue in dt.DataValues
                      where SensorIDs.Contains(dataValue.SensorID) &&
                            dataValue.DataID = d.DataID
                      select dataValue)
            select new { d, dV }).ToDictionary(o => o.d, o => o.dV.ToList());

这篇关于使用 linq 连接两个表,并填充它们的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to know if a field is numeric in Linq To SQL(如何在 Linq To SQL 中知道字段是否为数字)
Extract sql query from LINQ expressions(从 LINQ 表达式中提取 sql 查询)
LINQ Where in collection clause(LINQ Where in collection 子句)
Orderby() not ordering numbers correctly c#(Orderby() 没有正确排序数字 c#)
Why do I get quot;error: ... must be a reference typequot; in my C# generic method?(为什么我会收到“错误:...必须是引用类型?在我的 C# 泛型方法中?)
Strange LINQ Exception (Index out of bounds)(奇怪的 LINQ 异常(索引越界))