代码之家  ›  专栏  ›  技术社区  ›  Nick Louloudakis

从类型的IQueryable转换为转换类型的数组的最佳方法?

  •  1
  • Nick Louloudakis  · 技术社区  · 10 年前

    我正在使用实体框架,并希望将IQueryable的元素放入 转换 类型 有 NormalType 作为第一种类型 ConvertedType 作为转换的,“转换”是这样完成的:

    //Creates a NormalType object based on ConvertedType instance.
    NormalType nt = new NormalType (ctInstance);
    // Returns a new ConvertedType instance,
    //based on the content of the NormalType instance.
    ConvertedType ct = nt.getConvertedType();
    

    现在,我想将NormalType类型的列表转换为ConvertedType数组 ( IQueryable<NormalType> -> ConvertedType[] ).

    我的第一个想法是通过 IQueryable<NormalType> ,将数据放入 List<ConvertedType> 然后使用 ToArray() 方法:

    //Rest of code....
    List<ConvertedType> convertedTypeList = new List<ConvertedType>();
    //normalTypeIQueryable is of type IQueryable<NormalType>
    foreach(NormalType normalType in normalTypeIQueryable) 
    {
      convertedTypeList.Add(normalType.getConvertedType());
    }
    ConvertedType[] convertedTypeArray = convertedTypeList.ToArray();
    

    我的第二个想法是使用 ToList() , ConvertAll(...) 到阵列() 在一个衬垫中:

    normalTypeIQueryable.ToList().ConvertAll(n => n.GetConvertedType()).ToArray();
    

    我认为最后一个将通过转换导致不止一个循环。

    就性能而言,这两种方式中哪一种更好?还有更好的选择吗?

    提前谢谢。

    更新: GetConvertedType() 基于 正常类型(NormalType) 以“深度复制”方式包含。

    1 回复  |  直到 10 年前
        1
  •  3
  •   Jon    10 年前

    这很简单。您要做的是将源序列中的值投影到不同的值中,然后将生成的序列放入数组中。

    LINQ使用 Select ,因此,最简单、最自然、(至少只要您打算使用LINQ)最高效的编写方法是:

    var result = input.AsEnumerable().Select(i => i.GetConvertedType()).ToArray();
    

    这实际上等同于手册 foreach 循环。