Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.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#_.net_.net 3.5 - Fatal编程技术网

C# 将对象集合联接到逗号分隔的字符串中

C# 将对象集合联接到逗号分隔的字符串中,c#,.net,.net-3.5,C#,.net,.net 3.5,在代码的许多地方,我们都有对象集合,我们需要从中创建一个逗号分隔的列表。集合的类型各不相同:它可能是一个数据表,我们需要从中获得某个列,或者一个列表,等等 现在我们循环遍历集合并使用字符串连接,例如: string text = ""; string separator = ""; foreach (DataRow row in table.Rows) { text += separator + row["title"]; separator = ", "; } string.

在代码的许多地方,我们都有对象集合,我们需要从中创建一个逗号分隔的列表。集合的类型各不相同:它可能是一个数据表,我们需要从中获得某个列,或者一个列表,等等

现在我们循环遍历集合并使用字符串连接,例如:

string text = "";
string separator = "";
foreach (DataRow row in table.Rows)
{
    text += separator + row["title"];
    separator = ", ";
}
string.Join(", ", contactsCollection.Select(i => i.FirstName));

有更好的模式吗?理想情况下,我希望我们可以通过发送函数从每个对象获取正确的字段/属性/列来重用这种方法。

作为旁白:我要做的第一个修改是使用,而不仅仅是一个字符串-这将为您节省资源

static string ToCsv<T>(IEnumerable<T> things, Func<T, string> toStringMethod)
{
    StringBuilder sb = new StringBuilder();

    foreach (T thing in things)
        sb.Append(toStringMethod(thing)).Append(',');

    return sb.ToString(0, sb.Length - 1); //remove trailing ,
}
或:

列出客户=//假设客户有一个Name属性
Console.WriteLine(ToCsv(customers,c=>c.Name));

我手头没有编译器,但理论上它应该可以工作。众所周知,在理论上,实践和理论是一样的。实际上,它们不是。您可以编写一个函数,将IEnumerable转换为逗号分隔的字符串:

public string Concat(IEnumerable<string> stringList)
{
    StringBuilder textBuilder = new StringBuilder();
    string separator = String.Empty;
    foreach(string item in stringList)
    {
        textBuilder.Append(separator);
        textBuilder.Append(item);
        separator = ", ";
    }
    return textBuilder.ToString();
}
public string Concat(IEnumerable stringList)
{
StringBuilder textBuilder=新建StringBuilder();
字符串分隔符=string.Empty;
foreach(stringList中的字符串项)
{
textBuilder.Append(分隔符);
textBuilder.Append(项);
分隔符=“,”;
}
返回textBuilder.ToString();
}
然后,您可以使用LINQ查询您的集合/数据集/etc以提供stringList。

//使用System.Collections;
// using System.Collections;
// using System.Collections.Generic;
// using System.Linq

public delegate string Indexer<T>(T obj);

public static string concatenate<T>(IEnumerable<T> collection, Indexer<T> indexer, char separator)
{
    StringBuilder sb = new StringBuilder();
    foreach (T t in collection) sb.Append(indexer(t)).Append(separator);
    return sb.Remove(sb.Length - 1, 1).ToString();
}

// version for non-generic collections
public static string concatenate<T>(IEnumerable collection, Indexer<T> indexer, char separator)
{
    StringBuilder sb = new StringBuilder();
    foreach (object t in collection) sb.Append(indexer((T)t)).Append(separator);
    return sb.Remove(sb.Length - 1, 1).ToString();
}

// example 1: simple int list
string getAllInts(IEnumerable<int> listOfInts)
{
    return concatenate<int>(listOfInts, Convert.ToString, ',');
}

// example 2: DataTable.Rows
string getTitle(DataRow row) { return row["title"].ToString(); }
string getAllTitles(DataTable table)
{
    return concatenate<DataRow>(table.Rows, getTitle, '\n');
}

// example 3: DataTable.Rows without Indexer function
string getAllTitles(DataTable table)
{
    return concatenate<DataRow>(table.Rows, r => r["title"].ToString(), '\n');
}
//使用System.Collections.Generic; //使用System.Linq 公共委托字符串索引器(T obj); 公共静态字符串连接(IEnumerable集合、索引器、索引器、字符分隔符) { StringBuilder sb=新的StringBuilder(); foreach(集合中的T)sb.Append(索引器(T)).Append(分隔符); 返回某人删除(某人长度-1,1).ToString(); } //非泛型集合的版本 公共静态字符串连接(IEnumerable集合、索引器、索引器、字符分隔符) { StringBuilder sb=新的StringBuilder(); foreach(集合中的对象t)sb.Append(索引器((t)t)).Append(分隔符); 返回某人删除(某人长度-1,1).ToString(); } //示例1:简单整数列表 字符串getAllInts(IEnumerable listOfInts) { 返回连接(listOfInts,Convert.ToString,,); } //示例2:DataTable.Rows 字符串getTitle(DataRow行){返回行[“title”].ToString();} 字符串getAllTitles(数据表) { 返回连接(table.Rows,getTitle,'\n'); } //示例3:DataTable.Rows不带索引器函数 字符串getAllTitles(数据表) { 返回concatenate(table.Rows,r=>r[“title”].ToString(),'\n'); }
字符串strTest=“1,2,4,6”;
字符串[]Nums=strTest.Split(',');
Console.Write(Nums.Aggregate((第一,第二)=>first+”,“+second));
//输出:
//1,2,4,6
我喜欢这篇文章:

我必须把它做成一个扩展:

public static string ToCsv<T>(this IEnumerable<T> things, Func<T, string> toStringMethod)
公共静态字符串ToCsv(这是IEnumerable things,funct-toStringMethod)
用法(我收到所有电子邮件并将其转换为电子邮件字符串):

var list=Session.Find(“来自用户u,其中u.IsActive=true”).Cast();
return list.ToCsv(i=>i.Email);

在.NET4中,您只需执行
字符串.Join(“,”,table.Rows.Select(r=>r[“title”])
我找到了字符串。Join和lambda
Select有助于编写最少的代码

List<string> fruits = new List<string>();
fruits.Add("Mango");
fruits.Add("Banana");
fruits.Add("Papaya");

string commaSepFruits = string.Join(",", fruits.Select(f => "'" + f + "'"));
Console.WriteLine(commaSepFruits);

List<int> ids = new List<int>();
ids.Add(1001);
ids.Add(1002);
ids.Add(1003);

string commaSepIds = string.Join(",", ids);
Console.WriteLine(commaSepIds);

List<Customer> customers = new List<Customer>();
customers.Add(new Customer { Id = 10001, Name = "John" });
customers.Add(new Customer { Id = 10002, Name = "Robert" });
customers.Add(new Customer { Id = 10002, Name = "Ryan" });

string commaSepCustIds = string.Join(", ", customers.Select(cust => cust.Id));
string commaSepCustNames = string.Join(", ", customers.Select(cust => "'" + cust.Name + "'"));

Console.WriteLine(commaSepCustIds);
Console.WriteLine(commaSepCustNames);

Console.ReadLine();
List水果=新列表();
水果。添加(“芒果”);
水果。添加(“香蕉”);
水果。添加(“木瓜”);
字符串commaSepFruits=string.Join(“,”,fruits.Select(f=>“'+f+”);
控制台写入线(commaSepFruits);
列表ID=新列表();
同上(1001);
添加(1002);
同上(1003);
string commaSepIds=string.Join(“,”,id);
控制台写入线(commaSepIds);
列出客户=新列表();
添加(新客户{Id=10001,Name=“John”});
添加(新客户{Id=10002,Name=“Robert”});
添加(新客户{Id=10002,Name=“Ryan”});
字符串commaSepCustIds=string.Join(“,”,customers.Select(cust=>cust.Id));
字符串commaSepCustNames=string.Join(“,”,customers.Select(cust=>“'”+cust.Name+”);
控制台写入线(commaSepCustIds);
Console.WriteLine(commaSepCustNames);
Console.ReadLine();

以下是我最喜欢的答案,适合这个问题, 并更正了转换为ConvertAll:

string text = string.Join(", ", Array.ConvertAll(table.Rows.ToArray(), i => i["title"]));

对于集合,您也可以使用此方法,例如:

string text = "";
string separator = "";
foreach (DataRow row in table.Rows)
{
    text += separator + row["title"];
    separator = ", ";
}
string.Join(", ", contactsCollection.Select(i => i.FirstName));

您可以选择任何要分离的属性。

这就是我要找的,谢谢!这里的理论和实践不同,你需要两个重载方法(一个用于泛型,一个用于非泛型),就像Hosam Aly的答案一样。不过,你的答案要简单得多。这是最好的答案,尤其是如果你遵循BigBlondViking的改进,将其作为一种扩展方法。更干净,适用于复杂对象。这正是我想要实现的,谢谢!虽然我发现lambda表达式更具可读性(如在Matt的解决方案中),但我同意lambda表达式更具可读性,但到目前为止我只使用了.NET2.0。我希望能很快了解它们。您可能希望将分隔符更改为字符串而不是字符,但不要忘记将“sb.Remove”调用更改为“sb.Remove(sb.Length-separator.Length,separator.Length)”漂亮且干净。如果someList被声明为IList怎么办?它缺少ToArray()方法。@CristiDiaconescu:string.Join(“,”,somelist.Select(t=>t.ToString()).ToArray())我得到
System.Array不包含“Convert”的定义。
@JoshStodola:说什么?你想用JVM编译吗;p它从1.0开始就存在了。@leppie错了。它是,它是,它是。我想你的意思是
ConvertAll
Aggregate返回与输入值相同的数据类型,也就是说,据我所知,我无法将列表聚合为字符串。可能是table.Rows.Select(r=>r[“title”].ToString())。聚合((a,b)=>a+”,“+b)然后?而Join可能是我通常使用的方式
List<string> fruits = new List<string>();
fruits.Add("Mango");
fruits.Add("Banana");
fruits.Add("Papaya");

string commaSepFruits = string.Join(",", fruits.Select(f => "'" + f + "'"));
Console.WriteLine(commaSepFruits);

List<int> ids = new List<int>();
ids.Add(1001);
ids.Add(1002);
ids.Add(1003);

string commaSepIds = string.Join(",", ids);
Console.WriteLine(commaSepIds);

List<Customer> customers = new List<Customer>();
customers.Add(new Customer { Id = 10001, Name = "John" });
customers.Add(new Customer { Id = 10002, Name = "Robert" });
customers.Add(new Customer { Id = 10002, Name = "Ryan" });

string commaSepCustIds = string.Join(", ", customers.Select(cust => cust.Id));
string commaSepCustNames = string.Join(", ", customers.Select(cust => "'" + cust.Name + "'"));

Console.WriteLine(commaSepCustIds);
Console.WriteLine(commaSepCustNames);

Console.ReadLine();
string text = string.Join(", ", Array.ConvertAll(table.Rows.ToArray(), i => i["title"]));
string.Join(", ", contactsCollection.Select(i => i.FirstName));