将Linq .ToList()放到datatable中

时间:2013-05-09 14:06:35

标签: c# linq

我想将此语句的数据放入dictionary / datatable中。

            var distinctValues = datatable.AsEnumerable()
              .Select(row => new
              {
                  Employee = row.Field<string>("Employee")
              })
              .Distinct()
              .ToList();

请帮忙,我如何转换数据表中的distinctValues?

更新

如果有人知道找到明确值的更好方法,那么请建议。我想在c#函数中传递它,我不能将它们作为var。

传递

3 个答案:

答案 0 :(得分:2)

检查CopyToDataTable()扩展名方法。

编辑: 改为匹配Servy的评论。

答案 1 :(得分:1)

您想要的是能够根据选择器从序列中获取不同的项目,但保留项目与原始序列而不是选择器的结果。这通常被命名为DistinctByMoreLinq has an implementation,(经过微小修改)是:

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector)
{
    return source.DistinctBy(keySelector, null);
}

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
    return DistinctByImpl(source, keySelector, comparer);
}

private static IEnumerable<TSource> DistinctByImpl<TSource, TKey>(IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
    HashSet<TKey> knownKeys = new HashSet<TKey>(comparer);
    foreach (TSource element in source)
    {
        if (knownKeys.Add(keySelector(element)))
        {
            yield return element;
        }
    }
}

使用它以及CopyToDataTable方法将行转换回表格,您现在可以执行以下操作:

var distinctTable = datatable.AsEnumerable()
    .DistinctBy(row => row.Field<string>("Employee"))
    .CopyToDataTable();

答案 2 :(得分:0)

尝试这样的扩展方法,也许它不是那么快,但它非常简单:

public DataTable ToDataTable<T>(this List<T> items)
        {
            DataTable dataTable = new DataTable(typeof(T).Name);
            //Get all the properties
            PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo prop in Props)
            {
                //Setting column names as Property names
                dataTable.Columns.Add(prop.Name);
            }
             foreach (T item in items)
            {
                var values = new object[Props.Length];
                for (int i = 0; i < Props.Length; i++)
                {
                    //inserting property values to datatable rows
                    values[i] = Props[i].GetValue(item, null);
                }
                dataTable.Rows.Add(values);
            }
             //put a breakpoint here and check datatable
            return dataTable;
        }