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

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

        public static string ToListingCommaFormat(this List stringList)
        {
            switch(stringList.Count)
            {
                case 0:
                    return "";
                case 1:
                    return stringList[0];
                case 2:
                    return stringList[0] + " and " + stringList[1];
                default:
                    return String.Join(", ", stringList.GetRange(0, stringList.Count-1)) 
                        + ", and " + stringList[stringList.Count - 1];
            }
        }
    

    This is the method is faster than the 'efficient' Join method posted by Gabe. For one and two items, it is many times faster, and for 5-6 strings, it is about 10% faster. There is no dependency on LINQ. String.Join is faster than StringBuilder for small arrays, which are typical for human-readable text. In grammar, these are called listing commas, and the last comma should always be included to avoid ambiguity. Here is the resulting code:

    people.Select(x=> x.ID.ToString() + ":" + x.Name).ToList().ToListingCommaFormat();

提交回复
热议问题