In VB.NET I'm used to doing things like this when creating anonymous types (VB.NET anonymous types include the notion of Key Fields):
Dim prod1 = New With {
Key .Name = "paperclips",
Key .Price = 1.29,
.OnHand = 423
}
However, I haven't been able to find any way of doing this in C#, since it appears the Key
keyword is not supported.
Is there any way to indicate in C# that I only want to compare some of the fields in anonymous type when looking for equality?
Create a primary key to associate data between multiple tables. In the Navigation Pane, right click a table, and select Design View. Select the field or fields you want to use as the primary key. Select Design > Primary Key.
The customer ID field is the primary key. Access automatically creates an index for the primary key, which helps speed up queries and other operations. Access also ensures that every record has a value in the primary key field, and that it is always unique.
An entity key is a property or a set of properties of an entity type that are used to determine identity. The properties that make up an entity key are chosen at design time. The values of entity key properties must uniquely identify an entity type instance within an entity set at run time.
Configuring a primary key By convention, a property named Id or <type name>Id will be configured as the primary key of an entity. Owned entity types use different rules to define keys. You can configure a single property to be the primary key of an entity as follows: Data Annotations.
There is nothing like that in C#. In C#, all properties of anonymous types are read-only and participate in equality comparisons.
If you want to do something like this in C#, you will need to create your own (named) type.
There is no Key equivalent in c#.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With