C# 提高LINQ查询性能
假设有一个类C# 提高LINQ查询性能,c#,linq,dictionary,C#,Linq,Dictionary,假设有一个类 public class StopTime { public TimeSpan? ArrivalTime { get; set; } public TimeSpan? DepartureTime { get; set; } public string StopID { get; set; } public int StopSequence { get; set; } public string TripID { get; set; } }
public class StopTime
{
public TimeSpan? ArrivalTime { get; set; }
public TimeSpan? DepartureTime { get; set; }
public string StopID { get; set; }
public int StopSequence { get; set; }
public string TripID { get; set; }
}
我必须从CSV文件中读取数据并将其映射到所提到的类。CSV文件可以有许多记录,在我的例子中大约有500000条记录
在解析CSV文件并将数据映射到不同函数中的StopTime
列表后,我想基于TripId
过滤StopTimes
。
在我的场景中,StopTime
列表中大约有8000个TripId
s
我尝试使用以下代码创建列表的字典:
var TripIdStops = new Dictionary<string, List<StopTime>>();
foreach (var tripId in ListOfTripId)
{
TripIdStops.Add(tripId, StopTimes.Where(x=>x.TripID==tripsDistinct).ToList());
}
var TripIdStops=newdictionary();
foreach(ListOfTripId中的变量tripId)
{
添加(tripId,StopTimes.Where(x=>x.tripId==tripsDistinct.ToList());
}
要创建字典,此循环必须过滤StopTime
s,记住500000条记录和8000个TripID实例
然而,这是一项非常耗时的任务。有什么方法可以提高性能吗?听起来你想要一个:
或者先通过ListOfTripId
缩小范围:
var tripIdSet = new HashSet<string>(ListOfTripId);
var stopTimesByTripId = StopTimes.Where(st => tripIdSet.Contains(st.TripId))
.ToLookup(st => st.TripId);
var-tripIdSet=newhashset(ListOfTripId);
var stopTimesByTripId=StopTimes.Where(st=>tripIdSet.Contains(st.TripId))
.ToLookup(st=>st.TripId);
在这两种情况下,您只需迭代一次停止时间。听起来您需要:
或者先通过ListOfTripId
缩小范围:
var tripIdSet = new HashSet<string>(ListOfTripId);
var stopTimesByTripId = StopTimes.Where(st => tripIdSet.Contains(st.TripId))
.ToLookup(st => st.TripId);
var-tripIdSet=newhashset(ListOfTripId);
var stopTimesByTripId=StopTimes.Where(st=>tripIdSet.Contains(st.TripId))
.ToLookup(st=>st.TripId);
在这两种情况下,您只需要迭代一次StopTimes
。您可以创建一个表
表示每个映射到一个或多个值的键的集合
您可以改为创建一个表
表示每个映射到一个或多个值的键的集合
我建议改变循环:通过
停站时间
,做些什么
像这样:
var TripIdStops = new Dictionary<string, List<StopTime>>();
foreach (var time in StopTimes) {
List<StopTime> list;
if (TripIdStops.TryGetValue(time.TripID, out list))
list.Add(time);
else
TripIdStops.Add(time.TripID, new List<StopTime>() { time });
}
var TripIdStops=newdictionary();
foreach(停止时间中的var时间){
名单;
if(TripIdStops.TryGetValue(time.TripID,out列表))
列表。添加(时间);
其他的
添加(time.TripID,new List(){time});
}
我建议改变循环:通过停站时间
,做点什么
像这样:
var TripIdStops = new Dictionary<string, List<StopTime>>();
foreach (var time in StopTimes) {
List<StopTime> list;
if (TripIdStops.TryGetValue(time.TripID, out list))
list.Add(time);
else
TripIdStops.Add(time.TripID, new List<StopTime>() { time });
}
var TripIdStops=newdictionary();
foreach(停止时间中的var时间){
名单;
if(TripIdStops.TryGetValue(time.TripID,out列表))
列表。添加(时间);
其他的
添加(time.TripID,new List(){time});
}