【问题标题】:Merge List<T> objects [duplicate]合并 List<T> 对象 [重复]
【发布时间】:2013-09-16 15:52:28
【问题描述】:

我有一个 asp.net 应用程序,其中有 4 个列表集合对象

List<string> sTransID = new List<string>();
List<string> sOriginID = new List<string>();
List<string> sDestID = new List<string>();
List<string> sCourierID = new List<string>();

这些对象填充在应用程序的不同部分(在类内部,或后面的 aspx 代码等)。当列表元素大小增加时,页面性能会明显变慢。

在读取这些对象的值时,循环遍历这些对象的最快方法是什么(以避免必须遍历 4 个对象)?我可以将这些对象合并到父 List 对象中并循环通过父对象吗?

更新:
通过合并,我的意思是:

var Parent = List<sTransID>, List<sOriginID>, List<sDestID>, List<sCourierID>  
var GetLocation = Parent[0];  // will return TransID[0], Origin[0], DestID[0], CourierID[0]

【问题讨论】:

  • 更快吗?可能只是一点点。如果 search 是您的瓶颈,那么您应该使用更好的数据结构(更好 = 搜索效率更高)。 Hastable 或(如果适用)有序列表
  • 列表之间有什么关系?
  • sTransID.Union(sOriginID.Union(sDestID.Union(sCourierID))) ?
  • 为什么不能使用 linq?
  • @Csharp 您应该将其添加到您的问题中。

标签: c# asp.net collections


【解决方案1】:

我有一个合并dictionaries 的扩展方法。如果您为 Lists 修改它可能会有所帮助。

public static class DictionaryExtensions
{
    public static T MergeLeft<T, K, V>(this T me, params IDictionary<K, V>[] others)
        where T : IDictionary<K, V>, new()
    {
        var newMap = new T();

        foreach (var p in (new List<IDictionary<K, V>> { me }).Concat(others).SelectMany(src => src))
        {
            newMap[p.Key] = p.Value;
        }

        return newMap;
    }

}

如下使用:

var mergedDictionary = new Dictionary<string, string>().MergeLeft(dic1, dic2, dic3);

【讨论】:

    【解决方案2】:

    一种方法是在循环之前将列表连接在一起:

    var itemsToLoop = sTransID.Concat(sOriginID).Concat(sDestID).Concat(sCourierID);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 2023-04-09
      • 1970-01-01
      • 2016-10-03
      • 2021-11-12
      • 2018-11-13
      相关资源
      最近更新 更多