4

I have a datatable where I would like to move all the rows that have a certain firstname and lastname to the top of the table.

public DataTable SortByFirstNameAndLastNameMatch(DataTable table, string firstName, string lastName)
    {
        DataTable ret = new DataTable();
        foreach (DataRow dataRow in table.Rows)
        {
            if (dataRow["NomArtiste"].ToString().ToLower() == lastName.ToLower() && dataRow["PrenomArtiste"].ToString().ToLower() == firstName.ToLower())
            {
                ret.ImportRow(dataRow);
            }
        }

        ret.Merge(table);
        return RemoveDuplicateRows(ret, "AlbumID");
    }

Is there a way I can do this using a linq expression or a comparer without making a new datatable?

3
  • Are you trying to modify the order in the database? Or just get and ordered result? Commented Nov 5, 2013 at 19:41
  • Well, I guess see DataViews/DefaultView - that may work for you. (You must use the DataView and not the natural ordering, however!) Commented Nov 5, 2013 at 19:45
  • If you use .AsEnumerable() (msdn.microsoft.com/en-us/library/…) on the DataTable then you can apply all the LINQ sorting/filtering/transforming/etc. that you want on it. Commented Nov 5, 2013 at 19:47

3 Answers 3

3

You can create a new DataView on your DataTable and apply whatever sorting and filtering you see fit. See http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx for an example.

Alternatively you can do it with LINQ:

var sortedTableQuery = table.OrderBy(r => r["NomArtiste"].ToString() == lastName ? 0 : 1).ThenBy(r => r["PrenomArtiste"].ToString() == firstName ? 0 : 1).ThenBy(r => r["NomArtiste"].ToString()).ThenBy(r => r["PrenomArtiste"].ToString());
var a = sortedTableQuery.ToArray(); 
Sign up to request clarification or add additional context in comments.

Comments

2

In Linq, it would look something like this:

var sortedNames = unsortedNames.OrderBy(n => n == lastName ? 1 : 2).ThenBy(n => n == firstName ? 1 : 2));

Comments

0
DataView dv=datatable.DefaultView;
dv.Sort = "ColumnName Asc ,ColumnName Asc, ColumnName Asc , ColumnName Asc";
datatable=dv.toTable().Copy();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.