.Net - Join together all item of a list in a output string

后端 未结 4 1891
忘了有多久
忘了有多久 2021-02-11 14:31

How can I write a Linq expression (or anything else) that select item from a List and join them together ?

Example

IList data = new List<         


        
相关标签:
4条回答
  • 2021-02-11 14:34

    You can use aggregate when you need to join a list into a single aggregated object.

    string s = "";
    if(data.Count > 0)
      s = data.Aggregate((a, b) => a + ',' + b);
    
    0 讨论(0)
  • 2021-02-11 14:36

    You may be tempted to use Aggregate() if you're sticking with LINQ

    IList<int> data = new List<int>();
    
    data.Add(123);
    data.Add(456);
    
    var result = data.Select(x => x.ToString()).Aggregate((a,b) => a + "," + b);
    

    I wouldn't recommend this because as I found out the hard way this will fail if the list contains zero items - or was it if it had only 1 item. I forget, but it fails all the same :-)

    String.Join(...) is the best way
    

    In the example above where the datatype is NOT a string you can do this :

    string.Join(",", data.Select(x => x.ToString()).ToArray())
    
    0 讨论(0)
  • 2021-02-11 14:43

    Why not just go with (String.Join Method)

    string joined = String.Join(",", data.ToArray());
    

    But if it has to be LINQ, you could try

    string joinedLinq = data.Aggregate((i, j) => i + "," + j);
    
    0 讨论(0)
  • 2021-02-11 14:47

    As Anthony Pegram wrote String.Join<T>(delimiter, IEnumerable<T>) is the best solution in .NET 4!

    0 讨论(0)
提交回复
热议问题