tags:

views:

493

answers:

3

I have a datatable like

public DataTable functiongettable()
{
        DataTable dt = new DataTable();

        dt.Columns.Add("Name");
        dt.Rows.Add("Name1");
        dt.Rows.Add("Name5");
        dt.Rows.Add("Name6");
        dt.Rows.Add("Name3");
        dt.Rows.Add("Name3");
        dt.Rows.Add("Name6");
        dt.Rows.Add("Name3");
        dt.Rows.Add("Name5");
        dt.Rows.Add("Name5");

        return dt;
}

By using linq query I want to perform Sorting and need unique records.

I am doing like this

var query = from c in functiongettable().AsEnumerable().OrderBy("Name").Distinct() select c;

But getting error:

The type arguments for method 'System.Linq.Enumerable.OrderBy(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

How to solve this?

Thanks in advance

+1  A: 

Try specifying the DataRowComparer.Default in the Distinct statement.

UPDATE:

And use row.Field("Name") when sorting

UPDATE again:

var query = (from c in functiongettable().AsEnumerable()
            orderby c.Field<string>("Name")
            select c).Distinc(DataRowComparer.Default);
Johan Leino
+1  A: 

You need to pass a delegate to OrderBy, not a string.

Try this:

        var query = dt.AsEnumerable()
            .OrderBy(dr => dr.ItemArray[0] as string)
            .Distinct(DataRowComparer.Default).Select(dr => dr.ItemArray[0]);

        foreach (var item in query)
        {
            Console.WriteLine(item);
        }
bruno conde
A: 

You cannot pass String as the parameter in OrderBy(). You need to pass in the identity function like so:

functiongettable().AsEnumerable().OrderBy(x=>x.Field<string>("Name")).Distinct()

And I don't think you will get distinct results here, as the method Distinct() will use the default equality operator of the TSource, which in this case will be of the DataRow. It will not distinctively select based on the string value of your Name column.

Darnell