【问题标题】:Issue related to Finding an Index of Item in List<string>与在 List<string> 中查找项目索引相关的问题
【发布时间】:2015-05-26 14:33:20
【问题描述】:

我是 Linq 的新手..

我的代码中有List&lt;string&gt; 对象。我想让它用逗号分隔,所以我写了以下语法

string commaSepNames = string.Join(",",lstNames.select(s=>s+" Customer").ToList());

上述语法将导致在名称末尾附加"Customer" 用逗号分隔...

但现在我想在“客户”末尾附加数字(从 1 到列表中的项目数),如下所示:

约翰客户1, Ghanshyam 客户2, 渡轮客户3, ……等等……

我怎样才能在一个语法行中实现它? without using "for loop" or "foreach loop" ??

谢谢....

【问题讨论】:

    标签: c# linq list generics listiterator


    【解决方案1】:

    使用为您提供索引的Enumerable.Select 的重载:

    var names = lstNames.Select((s, index) => string.Format("{0} Customer{1}", s, index + 1));
    string commaSepNames = string.Join(",", names);
    

    如果您不使用 .NET 4,则需要一个数组:

    string commaSepNames = string.Join(",", names.ToArray());
    

    【讨论】:

      猜你喜欢
      • 2017-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多