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

后端 未结 17 1388
天命终不由人
天命终不由人 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:22

    Just for fun, here’s something that really uses functional LINQ — no loop and no StringBuilder. Of course, it’s pretty slow.

    var list = new[] { new { ID = 1, Name = "John" },
                       new { ID = 2, Name = "Mark" },
                       new { ID = 3, Name = "George" } };
    
    var resultAggr = list
        .Select(item => item.ID + ":" + item.Name)
        .Aggregate(new { Sofar = "", Next = (string) null },
                   (agg, next) => new { Sofar = agg.Next == null ? "" :
                                                agg.Sofar == "" ? agg.Next :
                                                agg.Sofar + ", " + agg.Next,
                                        Next = next });
    var result = resultAggr.Sofar == "" ? resultAggr.Next :
                 resultAggr.Sofar + " and " + resultAggr.Next;
    
    // Prints 1:John, 2:Mark and 3:George
    Console.WriteLine(result);
    

提交回复
热议问题