Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the return type of my linq query?

Tags:

.net

linq

I have two tables A & B. I can fire Linq queries & get required data for individual tables. As i know what each of the tables will return as shown in example. But, when i join both the tables i m not aware of the return type of the Linq query. This problem can be solved by creating a class which will hold ID,Name and Address properties inside it. but,everytime before writing a join query depending on the return type i will have to create a class which is not a convinient way Is there any other mathod available to achieve this

  private IList<A> GetA()
    {
        var query = from a in objA
                    select a;
        return query.ToList();
    }

    private IList<B> GetB()
    {
        var query = from b in objB
                    select b;
        return query.ToList();
    }

    private IList<**returnType**?> GetJoinAAndB()
    {
        var query = from a in objA
                    join b in objB
                    on a.ID equals b.AID
                    select new { a.ID, a.Name, b.Address };
        return query.ToList();
    }
like image 830
Ulhas Tuscano Avatar asked Feb 16 '11 07:02

Ulhas Tuscano


People also ask

How many types of LINQ query are there?

LINQ provides you three different ways to write a LINQ query in C# or VB.

What are the two forms of LINQ?

LINQ comes in two flavors – the Query Syntax and Method Syntax (aka Fluent Syntax).

What is LINQ query expression?

In LINQ, a query variable is any variable that stores a query instead of the results of a query. More specifically, a query variable is always an enumerable type that will produce a sequence of elements when it is iterated over in a foreach statement or a direct call to its IEnumerator. MoveNext method.


1 Answers

You've created an anonymous class - you can't really return it. A simple solution is to add a class to represent your type.

For example:

public class UserWithAddress
{
    public UserWithAddress(int id, string name, string address)
    {
        ID = id;
        Name = name;
        Address = address;
    }

    // you may have your own types here
    public int ID { get; set; }
    public String Name { get; set; }
    public String Address { get; set; }
}

And then:

private IList<UserWithAddress> GetJoinAAndB()
{
    var query = from a in objA
                join b in objB
                on a.ID equals b.AID
                select new UserWithAddress(a.ID, a.Name, b.Address);
    return query.ToList();
}
like image 54
Kobi Avatar answered Oct 08 '22 14:10

Kobi