c# - Linq 查询选择逗号分隔列表

标签 c# algorithm

我有一个对象列表,其中对象有一个字符串属性,它是一个逗号分隔的数字 ID 列表。

提取逗号分隔值并获取 int 数组的最有效方法是什么?

目前我的解决方案是这样的:

var allCsvs = objects
    .Select(o => o.IdCsv); // the IdCsv is a string property, ie "1,2,3,4,5"
var allIds = string.Join(",", allCsvs);
var idArray = allIds.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
    .Select(id => Convert.ToInt32(id));

关于如何提高性能的任何想法?

更新:

对象可能看起来像这样:

class MyClass {
    public string IdCsv { get; set; }
}

并且此类的实例可能会将其字符串属性 IdCsv 设置为如下所示:"1,2,3,4,5"

最佳答案

试试这个:

internal class Csv
{
    public string CommaSepList { get; set; }
}


var allCsvs =
    new List<Csv>
        {
            new Csv
                {
                    CommaSepList = "1,2,3,4,,5"
                },
            new Csv
                {
                    CommaSepList = "4,5,7,,5,,"
                },
        };

int[] intArray =
    allCsvs
        .SelectMany(c => c.CommaSepList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        .Select(int.Parse)
        .ToArray();

或者

int[] intArray =
    allCsvs
        .SelectMany(c => c.CommaSepList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse))
        .ToArray();

关于c# - Linq 查询选择逗号分隔列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14477036/

相关文章:

algorithm - 给定一组二维坐标系中的点,如果我们只访问所有点一次,如何计算最小距离和路径?

json - 范围匹配查找的数据结构

最大(最小(匹配))的算法?

c# - 如何使用 Linq 查询和 EF 从具有多个字段的表中仅检索一个字段

C#:以自定义百分比创建 CPU 使用率

c# - 如何在 C# 的 MongoDB 驱动程序中应用软删除过滤器?

c# - 用 C# 合成声音

c++ - 理解 C++ 算法二进制搜索背后的工作原理的问题

algorithm - 复制一个字符串 n 次最少需要多少次操作?

c# - 绕过 TextBox 的字符限制?