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,
The value you generate is called Anonymous Type and you can return it unless you return object
like:
private object 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();
}
There are two good solutions:
1. is to generate a class to match the output and generate it like Kobi solution
2. if you are using .net 4 you can return a dynamic
type like
private dynamic 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();
}
then you can use it later. You can search the internet about the advantage of using dynamic
keyword.
As you have created an anonymous(Anonymous types are generated by the compiler, so we cannot know the type name in our codes) class so that you can not return it.Create a separate class with three properties Id,Name and Address then returned it.
public class Contact
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
private IList<Contact> GetJoinAAndB()
{
var query = from a in objA
join b in objB
on a.ID equals b.AID
select new Contact{ a.ID, a.Name, b.Address };
return query.ToList();
}
Like Kobi said.
If you do not want to create a class specifically for this case, you can use a Tuple
. Only supported .Net 4 though.
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();
}