1

I am comparing Objects to see if they are equal, or have any differences.

If they are different, I want to store them together somehow, but I'm not sure how. There will be multiple Objects of the same type to be added.

Is something like:

List<T,T> possible?

So if I compare Object A with Object B, and they are not the same, I could call:

List.Add(A,B).

So I would know that each object at each element were related?

Hope this makes sense!

user3437721
  • 2,227
  • 4
  • 31
  • 61
  • 3
    Create a class with two properties or use a `List>` or `List>`. – Tim Schmelter Dec 17 '14 at 14:20
  • 1
    @Tim - huge respect to you, but if you're going to answer a question can you answer it rather than comment - otherwise those of us who do take the time to do so get accused of [copying the comment](http://stackoverflow.com/questions/27527639/adding-2-objects-to-a-list/27527696?noredirect=1#comment43483949_27527696). Thanks. – Jamiec Dec 17 '14 at 14:34

3 Answers3

5

You can either create a class with two properties or use Tuple<T1,T2>

The former would look like

list.Add( new MyObject(A,B) )

The latter would then look like

list.Add( Tuple.Create(A,B) );

In order to initialise this list one would need to know the types of A and B - but lets assume A is of type Foo and B is of type Bar the list would be initialised as

var list = new List<Tuple<Foo,Bar>>()
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • Example of how to create an Empty Tuple, as this will be an expanding list as I loop through all the Objects. I will keep adding them if they are different – user3437721 Dec 17 '14 at 14:22
  • @BhargavModi - no, copied from about 15 years of writing .NET code. \*rolleyes\* – Jamiec Dec 17 '14 at 14:23
  • How do you iniatilse the list in the latter example using the Tuple? var list = new List?> – user3437721 Dec 17 '14 at 14:26
  • @user3437721: you should get familiar with [generics](http://msdn.microsoft.com/en-us/library/ms172192%28v=vs.110%29.aspx). If you want a list full of strings use `new List()` if you want one for your custom class `Foo` use `new List()` and with tuples `new List>()`(presuming the type of both is string). – Tim Schmelter Dec 17 '14 at 14:27
1

There will be multiple Objects of the same type to be added.

Then it sounds like you want a List<List<T>> (basically a jagged array). If there is some "key" value (e.g. a property that you are comparing) that can be used to identify the groups of "equal" objects then a Dictionary<TKey,List<TValue>> might offer some performance improvements.

Note that if you already have a collection you can use the GroupBy Linq method to group "equal" objects together.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

You can use Tuple to store objects of different type

Tuple<type1,type2>
Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40