Reputation: 1670
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?
Upvotes: 4
Views: 128
Reputation: 37
DataView dv=datatable.DefaultView;
dv.Sort = "ColumnName Asc ,ColumnName Asc, ColumnName Asc , ColumnName Asc";
datatable=dv.toTable().Copy();
Upvotes: 0
Reputation: 11209
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();
Upvotes: 3
Reputation: 567
In Linq, it would look something like this:
var sortedNames = unsortedNames.OrderBy(n => n == lastName ? 1 : 2).ThenBy(n => n == firstName ? 1 : 2));
Upvotes: 2