LINQ list to sentence format (insert commas & “and”)

后端 未结 17 1436
天命终不由人
天命终不由人 2021-01-12 23:33

I have a linq query that does something simple like:

var k = people.Select(x=>new{x.ID, x.Name});

I then want a function or linq lambda,

17条回答
  •  情深已故
    2021-01-13 00:37

    This can be the way you can achieve your goal

    var list = new[] { new { ID = 1, Name = "John" }, 
                       new { ID = 2, Name = "Mark" }, 
                       new { ID = 3, Name = "George" }
                     }.ToList();
    
    int i = 0;
    
    string str = string.Empty;
    
    var k = list.Select(x => x.ID.ToString() + ":" + x.Name + ", ").ToList();
    
    k.ForEach(a => { if (i < k.Count() - 1) { str = str +  a; } else { str = str.Substring(0, str.Length -2) + " and " + a.Replace("," , ""); } i++; });
    

提交回复
热议问题