maro
maro

Reputation: 29

create a list Using combination of two types

I need to create a list in which each member is a combination of two types A and B. Is it possible? For example, assuming A and B:

class A
{
    int a1;
    string a2;
}

class B
{
    int b1;
    string b2;
}

I want to create:

List<A&B> SampleList;

in a way that A&B contains following properties:

    int a1;
    string a2;
    int b1;
    string b2;

Upvotes: 1

Views: 337

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1499900

Three options:

  • Create a new class or struct composing both:

    public class AAndB
    {
        private readonly A a;
        private readonly B b;
    
        public AAndB(A a, B b)
        {
            this.a = a;
            this.b = b;
        }
    
        // etc
    }
    
  • Use Tuple<A, B> to do the same kind of thing, but without creating a new type.

  • If you only need this in a single method, use an anonymous type, e.g.

    var mixed = as.Zip(bs, (a, b) => new { A = a, B = b });
    

Upvotes: 0

Dmitri Trofimov
Dmitri Trofimov

Reputation: 574

Try tuples: https://msdn.microsoft.com/en-us/library/dd268536(v=vs.110).aspx

Then you can use:

var list = new List<Tuple<int, string>>();
list.Add(new Tuple(2, "some text));

And read values like:

Console.WriteLine(list[0].Item1); // writes 2
Console.WriteLine(list[0].Item2); // writes "some text"

Upvotes: 2

Tobias Knauss
Tobias Knauss

Reputation: 3509

Solution 1: use 2 separate lists.
Solution 2: use a dictionary.
Solution 3: create a class C that holds A and B as (public) members and create a list of C.

Upvotes: 0

Related Questions