Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何制作外观自然的列表?_C#_Linq_List_Join - Fatal编程技术网

C# 如何制作外观自然的列表?

C# 如何制作外观自然的列表?,c#,linq,list,join,C#,Linq,List,Join,我所说的自然外观是指: 第1项、第2项、第3项和第4项 我知道你可以用字符串做一个逗号分隔的列表 第1项、第2项、第3项、第4项 但是你怎么能列出这样的清单呢?我有一个基本的解决方案: int countMinusTwo = theEnumerable.Count() - 2; string.Join(",", theEnumerable.Take(countMinusTwo)) + "and " + theEnumerable.Skip(countMinusTwo).First();

我所说的自然外观是指:

第1项、第2项、第3项和第4项

我知道你可以用
字符串做一个逗号分隔的列表

第1项、第2项、第3项、第4项

但是你怎么能列出这样的清单呢?我有一个基本的解决方案:

int countMinusTwo = theEnumerable.Count() - 2;
string.Join(",", theEnumerable.Take(countMinusTwo)) + "and " 
    + theEnumerable.Skip(countMinusTwo).First();

但我很肯定有更好的(更有效的)方法。任何人谢谢。

您应该计算一次大小并将其存储在变量中。否则每次都会执行查询(如果不是集合)。另外,如果您想要最后一项,
Last
更具可读性

string result;
int count = items.Count();
if(count <= 1)
    result = string.Join("", items);
else
{
    result = string.Format("{0} and {1}"
        , string.Join(", ", items.Take(counter - 1))
        , items.Last());
}

我会用绳子工作

假设你有:

string items = "item1, item2, item3, item4";
然后你可以做:

int lastIndexOf = items.LastIndexOf(",");
items = items.Remove(lastIndexOf);
items = items.Insert(lastIndexOf, " and");

那么输出会是什么样子呢?@Tigran输出在顶部。第一个引号块。=)您的代码是否会产生
“item1、item2和item3。”
?@Tim-使用的是有争议的。@Tim-嗯,在这种情况下,什么是或不是“自然”是非常主观的。即使我同意,像这样的逗号也是合乎逻辑的,“自然”是每个人最习惯的。因此,如果没有上下文,不使用它不能简单地被称为“不正确”。我会将其归类为“更好”,因为它更容易阅读,而且效率更高get@newStackExchangeInstance:如果进行扩展,可以为后缀(“and”、“or”等)添加可选参数。如果他有
“item1”
onlylastIndexOf将返回-1该怎么办。处理好,快点。有人计算复杂性!;)
int lastIndexOf = items.LastIndexOf(",");
items = items.Remove(lastIndexOf);
items = items.Insert(lastIndexOf, " and");