我有一个对象列表,其中对象有一个字符串属性,它是一个逗号分隔的数字 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/