C#按Datatable分组,并将每组的项目写入一个文本文件

本文关键字:文件 文本 一个 项目 分组 Datatable | 更新日期: 2023-09-27 18:26:17

我有一个有两列的数据表,一列是名称,另一列是组

示例-

Name     Group
John     HR,Finance
Tom      HR,
Jonna    Finance,
Adam     IT,
Rachael  Default,IT,

我想按组名对以上数据进行分组,然后按照将其写入文本文件

Start - HR
John
Tom
End
Start - Finance
John
Jonna
End
Start - IT
Adam 
Rachael  
End
Start - Default
Rachael
End

这就是我分组的方式,但无法思考如何绕过逗号分隔的多个组,然后使用这些信息写入上面的文本文件

  var result = from row in dt.AsEnumerable()
                group row by row.Field<string>("GroupName") into grp
                select grp.ToList();

如有任何帮助,我们将不胜感激。

C#按Datatable分组,并将每组的项目写入一个文本文件

开始

var result = dt.AsEnumerable()
    .SelectMany(row => row.Field<string>("Group").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries),
        (row, group) => new { group, row })
    .GroupBy(item => item.group);

样品使用

TextWriter writer = Console.Out; // File.CreateText(@"...");
foreach (var group in result)
{
    writer.WriteLine("Start - " + group.Key);
    foreach (var item in group)
        writer.WriteLine(item.row.Field<string>("Name"));
    writer.WriteLine("End");
    writer.WriteLine();
}
// sample data
var table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Group", typeof(string));
table.Rows.Add("John", "HR,Finance");
table.Rows.Add("Tom", "HR,");
table.Rows.Add("Jonna", "Finance,");
table.Rows.Add("Adam", "IT,");
table.Rows.Add("Rachael", "Default,IT,");
// get a distinct list of all the departments
var departments = table.AsEnumerable()
                       .SelectMany(r => r.Field<string>("Group").Split(new[] { ',' },
                                        StringSplitOptions.RemoveEmptyEntries))
                       .Distinct();
// loop through each department
foreach (string department in departments)
{
    // get any employees that are apart of the current department
    var employees = table.AsEnumerable()
                         .Where(r => r.Field<string>("Group").Contains(department));
    // write output according to OP's format
    Console.WriteLine("Start - {0}", department);
    foreach (var employee in employees)
        Console.WriteLine(employee.Field<string>("Name"));
    Console.WriteLine("End");
    Console.WriteLine();
}

输出:

Start - HR
John
Tom
End
Start - Finance
John
Jonna
End
Start - IT
Adam
Rachael
End
Start - Default
Rachael
End