Anonymous
Anonymous

Reputation: 9648

How to select same column's name from different table in Linq?

I've 2 tables with same column's name, for example, both table A and table B has column's name "Test". I want to select column Test from both table A and B to entity class. How can I do this?

Upvotes: 1

Views: 6837

Answers (2)

p.campbell
p.campbell

Reputation: 100557

It sounds like you want the two entities of TableA and TableB merged into a new object. You can use the .Select() extension method to create a new anonymous type, or into a class that you already have defined.

The requirement here is that you've got to find a common attribute between TableA and TableB. Here I assume you've got something like ID to match them together.

Anonymous Type

 var mergedTests =  from a in db.TableA
                    join b in db.TableB on a.CommonID equals b.CommonID
                    select new 
                           { TestFromA = a.Test, TestFromB = b.Test }
                    .ToList();

Existing Class

 List<MyCustomTests> mergedTests =  from a in db.TableA
                    join b in db.TableB on a.CommonID equals b.CommonID
                    select new MyCustomTests 
                       { TestName= a.Test, ShortName= b.Test }
                    .ToList();

Upvotes: 1

zerkms
zerkms

Reputation: 254886

class Program
{
    static void Main(string[] args)
    {
        var A = new Data[] {
            new Data { Test = 1, Relation = 1 },
            new Data { Test = 2, Relation = 2 },
            new Data { Test = 3, Relation = 3 },
            new Data { Test = 4, Relation = 4 },
            new Data { Test = 5, Relation = 5 },
        };

        var B = new Data[] {
            new Data { Test = 2, Relation = 2 },
            new Data { Test = 3, Relation = 3 },
            new Data { Test = 5, Relation = 5 },
        };

        var res = from a in A
                  join b in B on a.Relation equals b.Relation
                  select new { TestA = a.Test, TestB = b.Test };
    }
}

class Data
{
    public int Test;
    public int Relation;
}

Upvotes: 0

Related Questions