Join two tables using linq, and fill a Dictionary of them

后端 未结 3 895
情深已故
情深已故 2021-01-06 05:17

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

The records of Data(s) might be thousands (e.g. 500,00

3条回答
  •  我在风中等你
    2021-01-06 05:51

    You do not need a foreach loop in this case, you can use group join to create the dictionary straight from linq which should give you better performance.

    dict=(from DataValue d in dt.DataValues
               where sensorIDs.Contains(d.SensorID)
           group d by d.DataID 
               into datavalues
           join data in dt.Datas 
               on datavalues.Key equals data.DataId
           select new { 
             Key = data, 
             Value = datavalues
           }).ToDictionary(a=>a.Key,a=>a.Value.ToList());
    

    or you can use linq expression methods

    dict = dt.DataValues.Where(d=>sensorIDs.Contains(d.SensorID))
                .GroupBy(a=>a.DataID)
                 .Join(dt.Datas,a=>a.Key,a=>a.DataId,
                        (a,b)=>new{Key=b,Value=a.ToList()})
            .ToDictionary(a=>a.Key,a=>a.Value);
    

提交回复
热议问题