在DataTable上使用select distinct

时间:2014-04-03 19:07:50

标签: c# linq

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表达式转换为字符串类型,因为它不是a   代表类型linq。

我的代码中也有using System.Linq;语句。

1 个答案:

答案 0 :(得分:1)

您可以按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>方法中替换它。