【问题标题】:Easiest way to convert list to a comma separated string by a Specific Property?通过特定属性将列表转换为逗号分隔字符串的最简单方法?
【发布时间】:2013-11-25 05:02:44
【问题描述】:

我有一个自定义对象列表,实际上这些是我存储在 IEnumerable 集合中的实体。我想将列表转换为逗号分隔的字符串,但我只想要一个特定属性,如何从自定义对象列表中构建具有特定属性的逗号分隔字符串?

我知道我可以使用"Foreach / For (int i .... " 构建一个逗号分隔的列表 但我认为有一个简单和更好的方法 那么这种简单的方法是什么?

这是我的清单

IEnumerable<BAL.Category> categories = chklCategories.CheckedItems.Cast<BAL.Category>();
            //Category object has a property called Name , I want the list from that property

【问题讨论】:

    标签: c# .net linq entity-framework


    【解决方案1】:

    这很容易,不是吗?

    string sCategories = string.Join(",", categories.Select(x => x.Name));
    

    【讨论】:

      【解决方案2】:

      试试这个。

      通过使用此版本的string.Join&lt;string&gt; 方法,您可以在加入之前减少收藏的副本。

      static string CombineList(IEnumerable categories)
      {
        return string.Join<string>(",", categories.Select(x => x.Name));
      }
      

      【讨论】:

        猜你喜欢
        • 2013-02-04
        • 1970-01-01
        • 2016-08-03
        • 1970-01-01
        • 1970-01-01
        • 2011-09-28
        • 2010-09-17
        • 2011-01-03
        • 1970-01-01
        相关资源
        最近更新 更多