代码之家  ›  专栏  ›  技术社区  ›  Jobi Joy

使用LINQ解析列表<string>中的所有字符串

  •  466
  • Jobi Joy  · 技术社区  · 15 年前

    List<string> string 用分隔符?

    如果集合是自定义对象而不是 ? 想象一下我需要连接到 object.Name .

    9 回复  |  直到 7 年前
        1
  •  1116
  •   Sedat Kapanoglu johnnywhoop    4 年前
    String.Join(delimiter, list);
    

    这就足够了。

        2
  •  555
  •   Caius Jard    3 年前

    警告-严重的性能问题

    虽然这个答案确实产生了预期的结果,但与这里的其他答案相比,它的性能较差。在决定使用它时要非常小心


    string delimiter = ",";
    List<string> items = new List<string>() { "foo", "boo", "john", "doe" };
    Console.WriteLine(items.Aggregate((i, j) => i + delimiter + j));
    

    public class Foo
    {
        public string Boo { get; set; }
    }
    

    用法:

    class Program
    {
        static void Main(string[] args)
        {
            string delimiter = ",";
            List<Foo> items = new List<Foo>() { new Foo { Boo = "ABC" }, new Foo { Boo = "DEF" },
                new Foo { Boo = "GHI" }, new Foo { Boo = "JKL" } };
    
            Console.WriteLine(items.Aggregate((i, j) => new Foo{Boo = (i.Boo + delimiter + j.Boo)}).Boo);
            Console.ReadKey();
    
        }
    }
    

    items.Select(i => i.Boo).Aggregate((i, j) => i + delimiter + j)
    
        3
  •  137
  •   Caius Jard    3 年前

    注:此答案 不使用LINQ

    现代.NET(从.NET4开始)

    string.Join(delimiter, enumerable);
    

    这是针对可枚举的自定义对象:

    string.Join(delimiter, enumerable.Select(i => i.Boo));
    

    旧.NET(在.NET 4之前)

    这适用于字符串数组:

    string.Join(delimiter, array);
    

    这是一个列表<字符串>:

    string.Join(delimiter, list.ToArray());
    

    这是一个自定义对象列表:

    string.Join(delimiter, list.Select(i => i.Boo).ToArray());
    
        4
  •  57
  •   dev.bv    9 年前
    using System.Linq;
    
    public class Person
    {
      string FirstName { get; set; }
      string LastName { get; set; }
    }
    
    List<Person> persons = new List<Person>();
    
    string listOfPersons = string.Join(",", persons.Select(p => p.FirstName));
    
        5
  •  27
  •   Jacob Proffitt    15 年前

    List<string> myStrings = new List<string>{ "ours", "mine", "yours"};
    string joinedString = string.Join(", ", myStrings.ToArray());
    

    虽然不是LINQ,但它很管用。

        6
  •  9
  •   Peter Mortensen stimpy    5 年前

    List<string> items = new List<string>() { "foo", "boo", "john", "doe" };
    
    Console.WriteLine(string.Join(",", items));
    

    快乐编码!

        7
  •  8
  •   Jordão    14 年前

    我认为,如果在扩展方法中定义逻辑,代码的可读性将大大提高:

    public static class EnumerableExtensions { 
      public static string Join<T>(this IEnumerable<T> self, string separator) {  
        return String.Join(separator, self.Select(e => e.ToString()).ToArray()); 
      } 
    } 
    
    public class Person {  
      public string FirstName { get; set; }  
      public string LastName { get; set; }  
      public override string ToString() {
        return string.Format("{0} {1}", FirstName, LastName);
      }
    }  
    
    // ...
    
    List<Person> people = new List<Person>();
    // ...
    string fullNames = people.Join(", ");
    string lastNames = people.Select(p => p.LastName).Join(", ");
    
        8
  •  7
  •   Peter McG    15 年前
    List<string> strings = new List<string>() { "ABC", "DEF", "GHI" };
    string s = strings.Aggregate((a, b) => a + ',' + b);
    
        9
  •  4
  •   Peter Mortensen stimpy    5 年前

    我已经使用LINQ完成了这项工作:

    var oCSP = (from P in db.Products select new { P.ProductName });
    
    string joinedString = string.Join(",", oCSP.Select(p => p.ProductName));
    
        10
  •  2
  •   Welcor Forum999    4 年前

    String.Join

    • "" 当列表为空时。 Aggregate 将抛出异常。
    • 性能可能比
    • 与纯LINQ方法相比,与其他LINQ方法结合使用时更易于阅读 String.Join()

    var myStrings = new List<string>() { "a", "b", "c" };
    var joinedStrings = myStrings.Join(",");  // "a,b,c"
    

    public static class ExtensionMethods
    {
        public static string Join(this IEnumerable<string> texts, string separator)
        {
            return String.Join(separator, texts);
        }
    }
    
        11
  •  2
  •   Robrecht Dewaele    3 年前

    这个答案的目的是扩展和改进对基于LINQ的解决方案的一些提及。这本身并不是解决这一问题的“好”方法。只用 string.Join as suggested 当它适合你的需要。

    鉴于没有与所有这些要求相匹配的答案,我提出了一个基于LINQ的实现,它以线性时间运行,可用于任意长度的枚举,并支持元素到字符串的一般转换。

    那么,林克还是半身像?可以
    static string Serialize<T>(IEnumerable<T> enumerable, char delim, Func<T, string> toString)
    {
        return enumerable.Aggregate(
            new StringBuilder(),
            (sb, t) => sb.Append(toString(t)).Append(delim),
            sb =>
            {
                if (sb.Length > 0)
                {
                    sb.Length--;
                }
    
                return sb.ToString();
            });
    }
    

    此实现比许多替代方案更复杂,主要是因为我们需要在自己的代码中管理分隔符(分隔符)的边界条件。

    它应该以线性时间运行,最多遍历元素两次。

    一次用于生成要在第一位追加的所有字符串,零到一次用于生成最终结果 托斯特林 What is the Complexity of the StringBuilder.ToString() 有关更多信息,请参阅。

    最后的话

    只用 按照建议 如果它符合您的需要,请添加 当你需要先按摩的时候。

    这个答案的主要目的是说明使用LINQ检查性能是可能的。结果(可能)过于冗长,无法推荐,但它确实存在。

        12
  •  1
  •   Reza Jenabi    4 年前

    你可以用 Aggregate ,将字符串连接成单个字符分隔的字符串,但将抛出

    你可以用 具有 一串

    var seed = string.Empty;
    var seperator = ",";
    
    var cars = new List<string>() { "Ford", "McLaren Senna", "Aston Martin Vanquish"};
    
    var carAggregate = cars.Aggregate(seed,
                    (partialPhrase, word) => $"{partialPhrase}{seperator}{word}").TrimStart(',');
    

    string.Join 不在乎你是否传递了一个空集合。

    var seperator = ",";
    
    var cars = new List<string>() { "Ford", "McLaren Senna", "Aston Martin Vanquish"};
    
    var carJoin = string.Join(seperator, cars);