如何正确划分List <string>?

时间:2016-04-17 10:37:32

标签: c# .net string list

我有List<string> {"", "1,5,4", "h", "5,8", "1"}。我需要分成3 List<int>。这是我的代码:

var parseString = condition.Trim().Split(separator).ToList();
var numberSections = new List<string>();
var numberRow = new List<string>();
var numberCell = new List<string>();
foreach (var str in parseString) {
    if (int.TryParse(str.Substring(0, 1), out i) && numberSections.Count == 0) {
        numberSections.Add(str);
        parseString.Remove(str);
    }
    if (int.TryParse(str.Substring(0, 1), out i) && numberRow.Count == 0) {
        numberRow.Add(str);
        parseString.Remove(str);
    }
    if (int.TryParse(str.Substring(0, 1), out i) && numberCell.Count == 0) {
        numberCell.Add(str);
        parseString.Remove(str);
    }
}

但它不起作用。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

这是一个LINQ版本

var result = list.Select(x => x.Split(",".ToCharArray(), 
                               StringSplitOptions.RemoveEmptyEntries)) // now we have List<List<string>>
                .Select(x => x.Select(y =>
                {
                    int value;
                    var isInt = int.TryParse(y, out value);
                    return isInt ? value : (int?)null;
                })) // convert each element of inner list to null or its int values
                    // we have a List<List<int?>>
                .Where(x => x.Any() && x.All(y => y.HasValue)) // only select lists which contains only integers
                .ToList();