Choice of Data Structure - c#

I need to have a list(array, ect) of objects that have a static values. What is the best way (more usefull) to organize such data structure on c#?
Now, I am able to do it using two ways:
1) Enumarations with an additional parameters:
http://www.codeproject.com/KB/cs/stringenum.aspx
2) Create some class with needed fields and then create an array of different classes instances.
Please write what of methods is the best with comments why or provide other ideas how to do it

I think the data structure you adopt will be largely dependant on how you intend to use the static values.
If you are going to be doing a lot of comparisons, I would suggest an enumeration with custom attributes (as described in your link, but possibly taken further) to provide additional metadata. However, if the structure containing the static values is going to operate more like a series of choices (e.g. the Encoding class in System.Text) then a static class with fields marked as readonly would be a better option.

Tuples for objects with static values

Sounds like a classic example of a Dictionary, a simple Key-Value relationship
http://dotnetperls.com/dictionary-keys
http://en.wikipedia.org/wiki/Associative_array

Related

Merging Objects of different types

I have two objects (WS.Customer and EF.Customer). The reason for this is my vendor didn't expose all of the fields in their object (WS.Customer) and I need to insert and update into those fields.
I need to merge WS.Customer -> EF.Customer and later merge EF.Customer -> WS.Customer. EF.Customer will have some extra fields that WS.Customer won't have, but when the field names match - I want the values merged.
I also only want to merge values where the destination field is null, empty, or a default value in case of a Guid.
I know I could use to Linq to query each object and build the other, but is there a less verbose way of doing things? I have some other objects I need to use this approach for and don't feel like spending a weeks typing away.
Thanks
You can use one of the available object-to-object mappers library like AutoMapper or EmitMapper. They will take care of copying the data in both directions and skip fields if properly configured. For example with EmitMapper your code might look like this:
ObjectMapperManager.DefaultInstance
.GetMapper<WS.Customer, EF.Customer>(<your configuration object here>)
.Map(customerSource, customerDestination);
What do you mean by "merged"? I guess you need to "translate" from one instance to another, i.e. copy values when name and type of property matches. Please have a look at the implementation provided in ServiceStack, the extension method of object - TranslateTo method: https://github.com/ServiceStack/ServiceStack/blob/master/src/ServiceStack.Common/ReflectionExtensions.cs#L31

c# Tuple - What is a practical use of Tuple [duplicate]

This question already has answers here:
What and When to use Tuple? [duplicate]
(5 answers)
Closed 8 years ago.
I was looking at examples online of Tuple but I do not see any ideal use of it.
Meaning, it seems like a place to store variables.
Is there any practical use of Tuple. What I like to do is to pass in a value to the tuple and then have it return back 3 values which are all strings.
A Tuple is counter-part to a List.
While a List stores 0-N of the same type of item, a Tuple store 1-M of (possibly) different-typed items, where N is unbounded and M is statically fixed/defined.
Each of these items can be accessed in a strongly-typed manner by their name (or "index" as it happens to aligned).
They are thus similar to an anonymous type (actually, this is more like a "record" and not a "tuple" because the names can be arbitrarily chosen):
new { _0 = value0, _1 = value1, /* etc, as needed */ }
But the Tuple types are nominatively typed (they are backed by a bunch of different classes, just like Action or Func) and thus a specific Tuple type can be explicitly specified (e.g. in method signatures), which is something an anonymous type cannot be used for.
While I would say that the practical use of Tuples in C# is hampered by the lack of support (e.g. no decomposition, no application, etc.), they are used all the time in languages like Scala. The C# approach is generally to "create a new named type", but introduces the Tuple types as another available tool.
(A big place where Tuples are very useful is in intermediate computations -- but C# has anonymous types, which as seen with LINQ, fulfill this role quite well in most cases where the computations are done within the same method.)
Microsoft .NET 4.0 introduces type called Tuple which is a fixed-size collection of heterogeneously typed data. Like an array, a tuple has a fixed size that can't be changed once it has been created. Unlike an array, each element in a tuple may be a different type, and a tuple is able to guarantee strong typing for each element. This is really handy in scenario otherwise be achieved using custom types or struct.
Tuple s a container. you can store anything in it
For 3 items, it s called Triple. 4 items quadruple and so on.
Essentially you can just stick items in to it.
Here is an example.
The Tuple is a typed, immutable and generic construct. It is a useful container for storing conceptually related data. A simple class with commented members and additional methods is more useful for important things. But the Tuple can be used to store miscellaneous yet related information. Tuple falls short in the field of information hiding. It excels as a useful short-term container.
A practical use-case: let's say you want to pass around a list of structured data between different internal components of a software.
You can either declare a class which represents the structured data. In this case this class has to be dumb ideally, it'll only contain a bunch auto properties. You probably declare this in an interface as an embedded class (but then you have to prefix it with the interface name), or in the same namespace as the interface. At some point this maybe unnecessary plumbing code to define a sole class for this purpose.
Or you can use a tuple. This way you don't have to define a class for all of that, you can still remain type safe. You may loose the advantage of naming the properties, which can be problematic if you have many properties, maybe even from the same type.
More concrete example:
You want to set a column sorting for a TreeListView 3rd party component. You initiate the sorting from the controller object, which calls the right function (SortByColumns) on the view, which calls the function on your wrapper class around the 3rd party component, which calls the 3rd party components' proper functions.
If you define a DTO (dtata transfer object) object:
// Somewhere around an interface
class ColumnSortItem
{
string Caption { get; set; }
SortOrder Order { get; set; }
}
// Other places:
void SortByColumns(IList<ColumnSortItem> pColumnSortItems);
Tuples:
void SortByColumns(IList<Tuple<string, SortOrder>> pColumnSortItems);
I don't say tuples are always the better choice, but notice that we just had to declare a certain order and structure of items. Note, that in this concrete example it's pretty clear what is the string part of the tuple and what is the SortOrder part.
Addition: the actual calls of the function:
DTO
controller.SortByColumns(new List<ColumnSortItem>() {
new ColumnSortItem() { Caption = "Record", Order = SortOrder.Ascending },
new ColumnSortItem() { Caption = "Description", Order = SortOrder.Ascending }
});
Tuple
controller.SortByColumns(new List<Tuple<string, SortOrder>>() {
new Tuple<string, SortOrder>("Record", SortOrder.Ascending),
new Tuple<string, SortOrder>("Description", SortOrder.Ascending)
});
Tuple is a lightweight class to group several items together. It's an alternative to defining a new class any time you want to group two items together.
I find it useful when I want to return multiple items from a single method, but I can't use ref or out parameters.
It seems like it's there for temporary data storage; very localized use. These are occasions when writing your own class is either too time consuming or really not worth it because the data's life time is so short.
The .NET Framework 4 introduce the System.Tuple class for creating tuple objects that contain structured data. It also provides generic tuple classes to support tuples that have from one to eight components .
Here is example in C#
var objTupe = new System.Tuple<string, string, double,long>"Mike","Anderson",29000,9999999999);
Response.Write("Item1 : " + objTupe.Item1);
Response.Write("<br/>Item2 : " + objTupe.Item2);
Response.Write("<br/>Item3 : " + objTupe.Item3);
Response.Write("<br/>Item4 : " + objTupe.Item4);

design using a readonly class in c#

Small design question here. I'm trying to develop a calculation app in C#. I have a class, let's call it InputRecord, which holds 100s of fields (multi dimensional arrays) This InputRecordclass will be used in a number of CalculationEngines. Each CalculcationEngine can make changes to a number of fields in the InputRecord. These changes are steps needed for it's calculation.
Now I don't want the local changes made to the InputRecord to be used in other CalculcationEngine's classes.
The first solution that comes to mind is using a struct: these are value types. However I'd like to use inheritance: each CalculationEngine needs a few fields only relevant to that engine: it's has it's own InputRecord, based on BaseInputRecord.
Can anyone point me to a design that will help me accomplish this?
If you really have a lot of data, using structs or common cloning techniques may not be very space-efficient (e.g. it would use much memory).
Sounds like a design where you need to have a "master store" and a "diff store", just analogous to a RDBMS you have data files and transactions.
Basically, you need to keep a list of the changes performed per calculation engine, and use the master values for items which aren't affected by any changes.
The elegant solution would be to not change the inputrecord. That would allow sharing (and parallel processing).
If that is not an option you will have to Clone the data. Give each derived class a constructor that takes the base Input as a parameter.
You can declare a Clone() method on your BaseInputRecord, then pass a copy to each CalculationEngine.

How do you call these classes?

I'm trying to find a collective name for these non-"helper" classes which encapsulate method results (e.g. "SignupResult"), classes which hold multiple filter values (e.g. "ContactSearchFilter"), my SortDirection enum etc. -- I want to organize these correctly but can't find the correct name for these as a whole. Help?
Do they really have anything in common that would justify an own category name?
If you want to organize such files, I suggest putting them in the same folder/namespace as their dependencies, i.e. the enum belongs in the same namespace as the dictionary you use it with, SignupResult belongs together with the other signup process classes etc.
Depends on what you do with it. If you save it in the database, it's effectively an 'Entity'. If you just use it to pass variables around, I'd call it a 'Holder' class (though that's not really a formal term).
It's arguably interesting to consider that if you have too many of these, perhaps your design is not so great. You probably shouldn't be so-much passing results around, as doing actions based on things happening. JMHO. FWIW.
Perhaps creating a class called UserSession or something and have things like SignupResult/ContactSearchFilter as properties.

Enum in DataSet

I'm using DataSet to connect my C# program with SQL database. I want one of the columns to be an enumeration and I want it to act as an enum in my code. How can I do this?
I don't mean to burst everyone's bubble, but you can easily map an integer to an Enum using a Strongly Typed DataSet. I do it all the time. Rather than type the whole thing out here I have created an entry on my Blog describing in detail how to accomplish this.
I don't think you can. SQL Server doesn't have a concept of enums.
I would suggest using an ApplicationService layer that sits atop your repository layer. Then in your ApplicationService class (think of appropriate name for this class) you can transform the data that is returned from the repository layer to the appropriate enum value in your POCO object.
You might try using a strongly typed dataset.
Technically you can't. Enum's are static typed, they are designed to be used when you know all of the values at compile time. While there are some work-arounds, I would highly recommend that you do not do this.
Look at a unmodifiable dataset, this will give most of the benefits of a Enum and can be created on the fly.
While data cannot be stored as an Enum, they can be used as a fancy filter as long as the data in the database column is of an integer type. That is a complete different question if that is what you are after. Go to the MSDN page and read up on Enum's.

Categories