【问题标题】:LINQ - Add static text to each resultLINQ - 为每个结果添加静态文本
【发布时间】:2010-11-04 02:49:55
【问题描述】:

我有一个文件数组,但问题是根路径未附加到文件,所以使用下面的数据,我将如何将 linq 项附加到静态字符串?

string rootPath = "C:\\Users\\MyUserName";

List<string> files = new List<string>();
files.Add("\\My Documents\\File1.txt");
files.Add("\\My Documents\\File2.txt");

我本质上想要一个 Path.Combine(rootPath, x); 的列表我试过了,但没有运气:

var fileList = (from x in files
               select Path.Combine(rootPath, x)).ToList();

但它不附加rootPath,fileList与文件列表相同。

有什么想法吗?

【问题讨论】:

    标签: c# .net linq c#-4.0


    【解决方案1】:

    如果第二个参数有一个前导“\”,Path.Combine 显然会忽略第一个参数(这个blog entry 有更多信息)。

    这应该可行,它使用Path.Combine? operator 来说明第二个参数中的前导斜杠:

    var fileList = (from f in files 
                    select Path.Combine(rootPath, 
                    f.StartsWith("\\") ? f.Substring(1) : f)).ToList();
    

    【讨论】:

    • -1。处理路径时最糟糕的事情是连接字符串。
    • 我同意。我不能保证前导的 \\'s 在那里,因此我想使用 Path.Combine。
    • 嗯...这似乎是一个 Path.Combine 问题,不能让 \ 启动第二个参数吗?
    【解决方案2】:

    如果您更改,查询将正常工作

    "\\My Documents\\File1.txt" to @"My Documents\\File1.txt"

    原因在Donut提到的帖子中有所描述。

    因此,

    string rootPath = "C:\\Users\\MyUserName";
    
    List<string> files = new List<string>();
    files.Add(@"My Documents\\File1.txt");
    files.Add(@"My Documents\\File2.txt");
    
    var fileList = (from x in files select Path.Combine(rootPath, x)).ToList(); 
    
    OR
    
    var fileList = files.Select(i => Path.Combine(rootPath, i));
    

    工作正常。

    如果您根本不想更改现有源,然后使用 Path.Combine 代替 string.Concat

    例如

    string rootPath = "C:\\Users\\MyUserName";
    
    List<string> files = new List<string>();
    files.Add("\\My Documents\\File1.txt");
    files.Add("\\My Documents\\File2.txt");
    
    var fileList = (from x in files select string.Concat(rootPath, x)).ToList(); 
    
    OR
    var fileList = files.Select(i => string.Concat(rootPath, i));
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2016-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-27
      相关资源
      最近更新 更多