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

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

    I have refined my previous answer and I believe this is the most elegant solution yet.
    However it would only work on reference types that don't repeat in the collection (or else we'd have to use different means for finding out if item is first/last).

    Enjoy!

    var firstGuy = guys.First();
    var lastGuy = guys.Last();
    
    var getSeparator = (Func)
        (guy => {
            if (guy == firstGuy) return "";
            if (guy == lastGuy) return " and ";
            return ", ";
        });
    
    var formatGuy = (Func)
        (g => string.Format("{0}:{1}", g.Id, g.Name));
    
    // 1:John, 2:Mark and 3:George
    var summary = guys.Aggregate("",
        (sum, guy) => sum + getSeparator(guy) + formatGuy(guy));
    

提交回复
热议问题