Join collection of objects into comma-separated string

前端 未结 11 1249
无人共我
无人共我 2020-12-07 19:22

In many places in our code we have collections of objects, from which we need to create a comma-separated list. The type of collection varies: it may be a DataTable from whi

相关标签:
11条回答
  • 2020-12-07 19:48

    For collections you can use this method as well, for example:

    string.Join(", ", contactsCollection.Select(i => i.FirstName));
    

    You can select any property that you want to seperate.

    0 讨论(0)
  • 2020-12-07 19:49
    string strTest = "1,2,4,6";
    string[] Nums = strTest.Split(',');
    Console.Write(Nums.Aggregate<string>((first, second) => first + "," + second));
    //OUTPUT:
    //1,2,4,6
    
    0 讨论(0)
  • 2020-12-07 19:54

    In .NET 4 you can just do string.Join(", ", table.Rows.Select(r => r["title"]))

    0 讨论(0)
  • 2020-12-07 19:55

    I found string.Join and Lambda Select> helps to write minimum code.

            List<string> fruits = new List<string>();
            fruits.Add("Mango");
            fruits.Add("Banana");
            fruits.Add("Papaya");
    
            string commaSepFruits = string.Join(",", fruits.Select(f => "'" + f + "'"));
            Console.WriteLine(commaSepFruits);
    
            List<int> ids = new List<int>();
            ids.Add(1001);
            ids.Add(1002);
            ids.Add(1003);
    
            string commaSepIds = string.Join(",", ids);
            Console.WriteLine(commaSepIds);
    
            List<Customer> customers = new List<Customer>();
            customers.Add(new Customer { Id = 10001, Name = "John" });
            customers.Add(new Customer { Id = 10002, Name = "Robert" });
            customers.Add(new Customer { Id = 10002, Name = "Ryan" });
    
            string commaSepCustIds = string.Join(", ", customers.Select(cust => cust.Id));
            string commaSepCustNames = string.Join(", ", customers.Select(cust => "'" + cust.Name + "'"));
    
            Console.WriteLine(commaSepCustIds);
            Console.WriteLine(commaSepCustNames);
    
            Console.ReadLine();
    
    0 讨论(0)
  • 2020-12-07 19:57

    I love Matt Howells answer in this post:

    I had to make it into an extension:

    public static string ToCsv<T>(this IEnumerable<T> things, Func<T, string> toStringMethod)
    

    Usage: [ I am getting all the emails and turning them into a csv string for emails ]:

    var list = Session.Find("from User u where u.IsActive = true").Cast<User>();
    
    return list.ToCsv(i => i.Email);
    
    0 讨论(0)
提交回复
热议问题