I am trying to sort the array of primary keys from a datatable. I can't find any examples that match what I'm trying to do.
I need to compare two arrays of datacolumns. This requires sorting (at least using the only method I can devise).
I will be posting an answer to my question here: How to find the differences between two datatables
I am trying to make an efficient solution. I can copy the names to separate arrays, sort and compare them, but that method makes difficult to maintain code. If that's the only way, then I'll do it, but these method names hint to me that there is a better way.
The datatables are populated and the PrimaryKey arrays are populated correctly. However I can't get these methods to work:
DTS.PrimaryKey.ToList().Sort(Function(x, y) x.Caption.CompareTo(y.Caption))
DTT.PrimaryKey.ToList().Sort(Function(x, y) x.Caption.CompareTo(y.Caption))
or these:
DTS.PrimaryKey.OrderBy(Function(c) c.Caption)
DTT.PrimaryKey.OrderBy(Function(c) c.Caption)
Before and after I get the same results:
?DTS.PrimaryKey(0).Caption
"Manufacturer"
?DTS.PrimaryKey(1).Caption
"Make"
?DTT.PrimaryKey(0).Caption
"Manufacturer"
?DTT.PrimaryKey(1).Caption
"Style"
Both DTS and DTT are defined as System.Data.DataTable. I created a couple of simple tables for testing:
CREATE TABLE [dbo].[AAA](
[Manufacturer] [nchar](10) NOT NULL,
[Make] [nchar](10) NOT NULL,
[Color] [nchar](10) NULL,
CONSTRAINT [PK_AAA] PRIMARY KEY CLUSTERED
(
[Manufacturer] ASC,
[Make] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
AND
CREATE TABLE [dbo].[AAA](
[Manufacturer] [nchar](10) NOT NULL,
[Style] [nchar](10) NOT NULL,
[Color] [nchar](10) NULL,
CONSTRAINT [PK_AAA] PRIMARY KEY CLUSTERED
(
[Manufacturer] ASC,
[Style] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
I don't care what order they are in as (ascending or descending) long as its some sort of order:
?DTS.PrimaryKey(0).Caption
"Make"
?DTS.PrimaryKey(1).Caption
"Manufacturer"
?DTT.PrimaryKey(0).Caption
"Manufacturer"
?DTT.PrimaryKey(1).Caption
"Style"
OR
?DTS.PrimaryKey(0).Caption
"Manufacturer"
?DTS.PrimaryKey(1).Caption
"Make"
?DTT.PrimaryKey(0).Caption
"Style"
?DTT.PrimaryKey(1).Caption
"Manufacturer"
EDIT:
I got the sorting to work using this code:
Dim s = DTS.PrimaryKey.OrderBy(Function(c) c.Caption)
Dim t = DTT.PrimaryKey.OrderBy(Function(c) c.Caption)
But I don't like to write code that leaves the programmer that follows me guessing. I would prefer to explicitly define these variables. When I check the type I get:
"System.Linq.OrderedEnumerable`2[System.Data.DataColumn,System.String]"
Which looks kinda bizarre. Plus I can't seem to explicitly define a variable of that type. This seems to fly in the face of strongly typed variables.