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();
}
LINQ provides you three different ways to write a LINQ query in C# or VB.
LINQ comes in two flavors – the Query Syntax and Method Syntax (aka Fluent Syntax).
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With