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

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

    Here's a method that doesn't use LINQ, but is probably as efficient as you can get:

    public static string Join(this IEnumerable list,
                                 string joiner,
                                 string lastJoiner = null)
    {
        StringBuilder sb = new StringBuilder();
        string sep = null, lastItem = null;
        foreach (T item in list)
        {
            if (lastItem != null)
            {
                sb.Append(sep);
                sb.Append(lastItem);
                sep = joiner;
            }
            lastItem = item.ToString();
        }
        if (lastItem != null)
        {
            if (sep != null)
                sb.Append(lastJoiner ?? joiner);
            sb.Append(lastItem);
        }
        return sb.ToString();
    }
    
    Console.WriteLine(people.Select(x => x.ID + ":" + x.Name).Join(", ", " and "));
    

    Since it never creates a list, looks at an element twice, or appends extra stuff to the StringBuilder, I don't think you can get more efficient. It also works for 0, 1, and 2 elements in the list (as well as more, obviously).

提交回复
热议问题