当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Performing operations on a collection of string arrays

问题描述:

I am reading a file that contains rows like

pathName; additionalString; maybeSomeNumbers

I read it using

var lines = File.ReadAllLines(fileListFile);

var fileListEntries = from line in lines

where !line.StartsWith("#")

select line.Split(';').ToArray();

This works well so far. However I would like to change the drive letter in the pathName. I could convert fileListEntries to an array and loop across elements [i][0], but is there a way that I could do this operation on the collection directly?

网友答案:

Use the LINQ extension method syntax in order to be able to use code blocks { ... } in the lambda expressions. If you do so, you have to include an explicit return-statement.

var fileListEntries = lines
    .Where(l => !l.StartsWith("#"))
    .Select(l => {
        string[] columns = l.Split(';');
        if (Path.IsPathRooted(column[0])) {
            string root = Path.GetPathRoot(columns[0]);
            columns[0] = Path.Combine(@"X:\", columns[0].Substring(root.Length));
        }
        return columns;
    })
    .ToArray();
网友答案:

I think you can do it inline with the LINQ.

File.ReadAllLines() returns a string array, so you should be able to perform Replace() on the line from the collection.

var replace = "The string to replace the drive letter";
var lines = File.ReadAllLines(fileListFile);
var fileListEntries = from line in lines
                      where !line.StartsWith("#")
                      select (line.Replace(line[0], replace).Split(';')).ToArray();
网友答案:

You could just call a method in your select that modifies the text in the manner that you would like.

        static void Main(string[] args)
        {
            var fileListEntries = from line in lines
                                  where !(line.StartsWith("#"))
                                  select ( ModifyString(line));

        }

        private static string[] ModifyString(string line)
        {
            string[] elements = line.Split(';');
            elements[0] = "modifiedString";
            return elements;
        }
网友答案:
lines.Where(l => !l.StartsWith("#").
      Select(l => string.Concat(driveLetter, l.Substring(1))).
      Select(l => l.Split(';');
分享给朋友:
您可能感兴趣的文章:
随机阅读: