2012-12-20 26 views
1

我有一个C#列表,我想创建一个逗号分隔字符串。我已经找到了解决这个问题的其他答案,但是我的具体情况是我只想使用列表中的一部分值来创建字符串。从C#列表中的字符串部分创建逗号分隔的字符串

如果我的列表中包含这些值:

“富” “酒吧” “汽车”

,我想创建一个字符串

Foo, Bar and Car. 

我可以使用此代码:

string.Format("{0} and {1}.", 
       string.Join(", ", myList.Take(myList.Count - 1)), 
       myList.Last()); 

但是,我的清单实际上是由JSON值,像这样

{ Name = "Foo" } 
{ Name = "Bar" } 
{ Name = "Car" } 

所以在上面的代码的结果:

{ Name = "Foo" }, { Name = "Bar" } and { Name = "Car" }. 

我将如何构建字符串,这样我只能在列表中使用的FooBarCar值?

更新

由于@StevePy,这是我结束了:

string.Format("{0} and {1}.", 
       string.Join(", ", myList.Select(x => x.Name).ToList().Take(myList.Count - 1)), 
       myList.Select(x => x.Name).ToList().Last()); 
+1

是您的列表中列出和每个字符串的类型为“{名称=‘富’}”? – ryadavilli

+0

那么你需要什么样的实际输出?你会包括'和'到你的JSON响应? – Ulises

+0

你可能想看看这个:http://stackoverflow.com/questions/5409890/formatting-a-string-using-values-from-a-generic-list-by-linq –

回答

1

LINQ的应该有所帮助。

var nameList = myList.Select(x=>x.Name).ToList(); 
+0

最佳答案,让我走下正确的道路。 – TMC

0

可以使用JsonConvert.toString让你列表项的值,如果您使用JSON序列化,你可以如果你需要使用字符串操作使用JsonConvert.Deserialization

+0

你可能可以提供一些代码示例为此值得成为一个答案? – horgh

2

,刚刚抢每串的,String.IndexOfString.LastIndexOf必要组成部分的方法,例如:

List<string> myList = new List<string> { 
    "{ Name = \"Foo\" }", 
    "{ Name = \"Bar\" }", 
    "{ Name = \"Car\" }" 
}; 

var temp = myList.Select(x => 
    { 
     int index = x.IndexOf("\"") + 1; 
     return x.Substring(index, x.LastIndexOf("\"") - index); 
    }) 
    .ToList(); 

string result = string.Format("{0} and {1}.", 
           string.Join(", ", temp.Take(myList.Count - 1)), 
           temp.Last()); 
0

我建了一个方法,它会为你做这个:

static string ConvertToMyStyle(List<string> input) 
{ 
    string result = ""; 

    foreach(string item in input) 
    { 
     if(input.IndexOf(item) != input.ToArray().Length-1) 
      result += item + ", "; 
     else 
      result += "and " + item + "."; 
    } 
    return result; 
} 
0

这种处理单个项目的情况下

protected string FormatWithOxfordCommas(List<string> reasons) 
     { 
      string result = ""; 
      if (reasons.Count == 1) 
       result += reasons[0]; 
      else 
      { 
       foreach (string item in reasons) 
       { 
        if (reasons.IndexOf(item) != reasons.Count - 1) 
         result += item + ", "; 
        else 
         result += "and " + item + "."; 
       } 
      } 
      return result; 
     }