c# - 在 C# 中延迟转换 IReadOnlyList

标签 c# list

我希望能够做这样的事情来建立一个 网格数据结构。

IReadOnlyList<Point> points;
IReadOnlyList<IReadOnlyList<int>> triangles;

其中三角形是点列表中的索引。给定一个索引 三角形 ''ti'' 我们可以很容易地找到这些点

IEnumerable<Point> points = triangles[ti].Select(pi=>points[pi])

但是我希望能够定义一个方便的结构

IReadOnlyList<IReadOnlyList<Point>> trianglesAsPoints;

所以我可以做

IEnumerable<Point> points = triangles[ti]

最明显的方法是创建一个类似 linq 的选择器

IReadOnlyList<T> Select( this IReadOnlyList<U> This
                             , Func<U,T> selector)

它返回一个实例,其类重写了以下方法和 调用选择器

public interface IReadOnlyList<out T> : IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable
{
    // Summary:
    //     Gets the element at the specified index in the read-only list.
    //
    // Parameters:
    //   index:
    //     The zero-based index of the element to get.
    //
    // Returns:
    //     The element at the specified index in the read-only list.
    T this[int index] { get; }
}

这种模式的标准库或 nuget 中是否存在这样的工厂? 请注意,我不希望 IEnumerable 作为结果,因为我会失去索引能力 和 Count 属性,我只是想懒惰地转换值,这意味着 预先将所有值复制到新的列表实例。

最佳答案

我不相信框架中有任何东西可以做到这一点,不。自己实现显然相当容易,但我相信您必须这样做。完全有可能存在执行此操作的第 3 方库,但由于 IReadOnlyCollection 仅在 .NET 4.5 中,因此与接口(interface)已经存在一段时间相比,这种可能性更小。

不过,我建议将其命名为 Select 以外的名称 - 我会使用 ProjectView 或类似名称。当然,这意味着它不适用于 LINQ 查询表达式,但阅读代码的任何人都会更清楚它只是Enumerable.Select

关于c# - 在 C# 中延迟转换 IReadOnlyList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15379253/

相关文章:

c# - 从字体 migradoc/pdsharp 获取表格列的文本宽度

c# - 从属性构造函数中抛出异常

c# - 使用 Microsoft Interop 读取和写入 excel 单元格

c# - 通过 FTP 代理的 FTP

python - 算法:将向量添加到列表中同时避免嵌套

java - 在 arraylist for 循环中执行 Collections.swap() 是否安全?

java - 从另一个类访问列表

c# - 为什么使用 AddScoped() 而不是 AddSingleton()?

c++ - 允许用户在内部实现链表时与 std::strings 交互?

python - 删除列表的许多元素(python)