public static DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader)
{
string header = isFirstRowHeader ? "Yes" : "No";
string pathOnly = Path.GetDirectoryName(path);
string fileName = Path.GetFileName(path);
string sql = @"SELECT * FROM [" + fileName + "]";
using (OleDbConnection connection = new OleDbConnection(
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties="Text;HDR=" + header + """))
using (OleDbCommand command = new OleDbCommand(sql, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
return dataTable;
}
}
static void Main(string[] args)
{
var dir = AppDomain.CurrentDomain.BaseDirectory + @"classes.csv";
var test = GetDataTableFromCsv(dir, true);
var totalclasses = test.Rows.Count;
Console.Write("Number of Classes: " + totalclasses);
Console.WriteLine();
test.Columns[0].ColumnName = "Studios";
Console.Write("Col1: " + test.Columns[0].ColumnName);
Console.WriteLine();
Console.Write("Col2: " + test.Columns[1].ColumnName);
}
这是我到目前为止的代码。下一步是浏览名为"studios"的列,并找出有多少个不同的值。我将如何做到这一点?
我一直在尝试,但得到:
无法将 lambda 表达式转换为字符串类型,因为它不是 委托类型 LINQ。
我的代码中也有using System.Linq;
语句。
您可以
按列分组Studios
然后获取每个工作室名称的计数,例如:
var distinctValues = test.AsEnumerable()
.GroupBy(r => r.Field<int?>("Studios"))
.Select(grp => new
{
Studio = grp.Key,
Count = grp.Count(),
})
.ToList();
foreach (var item in distinctValues)
{
Console.WriteLine("Studio : {0}, Number: {1}", item.Studio, item.Count);
}
如果您的列类型与字符串不同,请在Field<T>
方法中替换它。