Is is possible to have a linq query that populates a class with List for any outer join subqueries?
I've tried various variations of this, but can't get it to work.
Another option would be to populate the class by having more queries, but that would be bad performance wise.
Here's an example, where I try to populate MyClass, using a single query
var result = from p in PersonTable
join cars in CarTable on p.id equals cars.id_person into carsGroup.DefaultIfEmpty()
select new MyClass
{
Person = new Person
{
Id = p.id,
Name = p.name
},
Cars = new List<Car>()
{
Id = carsGroup....??
}
}
public class MyClass
{
public Person Person { get; set; }
public List<PersonCar> Cars { get; set; }
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public class PersonCar
{
public int Id { get; set; }
pubint int IdPerson {get; set;}
public string Description { get; set; }
}
The LINQ query you have provide is incorrect. The following is a Test that will demonstrate functionality that you're probably looking for:
[TestMethod]
public void TestMethod1()
{
var PersonTable = new List<Person>
{
new Person
{
Id = 1,
Name = "Test1"
},
new Person
{
Id = 2,
Name = "Test2"
},
};
var CarTable = new List<PersonCar>
{
new PersonCar
{
Id = 1,
IdPerson = 2
},
new PersonCar
{
Id = 2,
IdPerson = 3
}
};
var result = (from person in PersonTable
join cars in CarTable on person.Id equals cars.IdPerson into carsGroup
from args in carsGroup.DefaultIfEmpty()
select new MyClass
{
Person = person,
Cars = carsGroup.ToList()
}).ToList();
Assert.AreEqual(2, result.Count);
Assert.AreEqual(1, result.Count(res => res.Cars.Count == 0));
Assert.AreEqual(1, result.Count(res => res.Cars.Count == 1));
}
Related
I have two tables
Person: { PersonId, Name }
Position: { PositionId, PositionName }
They are linked together through a lookup table [PersonPosition] { PersonId, PositionId }
The idea is one person can have 0 or more position.
How can I write entity query in C# to left outer join Person with Position through the [PersonPosition] lookup, and produce result like this:
[
{
PersonId: "100":
Position: ["Dev, QA"]
},
{
PersonId: "200";
Position: ["Dev"];
},
{
PersonId: "300";
Position: null;
},
]
Thanks,
You can do it with 2 LINQ queries (still might be not an optimal solution)
using System;
using System.Linq;
namespace AppTest
{
class Program
{
static void Main(string[] args)
{
var persons = new Person[]
{
new Person { Id = 100, Name = "Alpha"},
new Person { Id = 200, Name = "Beta"},
new Person { Id = 300, Name = "Gamma"}
};
var positions = new Position[]
{
new Position { Id = 1, Name = "Dev"},
new Position { Id = 2, Name = "QA"},
new Position { Id = 3, Name = "BA"}
};
var personPositions = new PersonPosition[]
{
new PersonPosition { PersonId=100, PositionId =1},
new PersonPosition { PersonId=100, PositionId =2},
new PersonPosition { PersonId=200, PositionId =2},
};
var positionsJoin = from position in positions
join personPositiontion in personPositions on position.Id equals personPositiontion.PositionId
select new
{
personPositiontion.PersonId,
position.Name
};
var result = from person in persons
join personPositiontion in positionsJoin on person.Id equals personPositiontion.PersonId into jointTable
from joint in jointTable.DefaultIfEmpty()
select new
{
person.Id,
person.Name,
PositionName = joint?.Name
};
foreach (var line in result.ToArray())
{
Console.WriteLine($"id:{line.Id}, name:{line.Name}, position:{line.PositionName}");
}
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Position
{
public int Id { get; set; }
public string Name { get; set; }
}
public class PersonPosition
{
public int PersonId { get; set; }
public int PositionId { get; set; }
}
}
How can I get a reference to the 'parent' object in the Linq below. Something like the way EF does it when you query for objects that are of EF Classes?
void Main()
{
IEnumerable<SomeModel> Brands = ....;
var list = Brands
.Select(b => new BrandModel()
{
ID = b.ID,
BrandName = b.Name,
Locations = b.Locations.Select(l => new LocationModel()
{
ID = l.ID,
LocationName = l.Name,
Brand = *here I would want the Brand object of this Location*
}).ToList()
}).ToList();
}
private class BrandModel
{
public int ID { get; set; }
public string BrandName { get; set; }
public List<LocationModel> Locations { get; set; }
}
private class LocationModel
{
public int ID { get; set; }
public string LocationName { get; set; }
public BrandModel Brand { get; set; }
}
You can create your BrandModel in two steps. First create it without locations, then set locations to it
To do so you need to convert your lambda b => new BrandModel() to block of statements b => { return new BrandModel() }. Try this code:
.Select(b =>
{
var model = new BrandModel
{
ID = b.ID,
BrandName = b.Name
};
model.Locations = b.Locations.Select(l => new LocationModel
{
Brand = model
}).ToList();
return model;
});
I have retrieve a list of employees. my employee class columns(employeeId, lastname, genderid)
List<m_employees> Items = new List<m_employees>
{
new m_employees{ employeeid = 1, lastname = "mike", genderid = 1 },
new m_employees{ employeeid = 2, lastname = "jeni", genderid = 2 }
};
then i have my gender class columns (id, title)
List<m_genders> genders = new List<m_genders>
{
new m_genders{ id = 1, title = "Male" },
new m_genders{ id = 2, title = "Female" }
};
//then i tried joining the retrieved list of employees to the genders
var x = from emp in Items
join sex in genders
on emp.genderid equals sex.id
into a from b in a.DefaultIfEmpty(new m_genders())
select new
{
emp.lastname,
emp.genderid,
sex = b.title
};
red error line is showing to the keyword join and says "the type of one of the expressions in the join clause is incorrect..."
how can i join them properly?
This happens because types emp.genderid, sex.id are different and you need to cast or convert them explicitly like that:
(int)emp.genderid equals sex.id
I was able to reproduce the error with the following class definition:
class m_genders
{
public int id { get; set; }
public string title { get; set; }
}
class employee
{
public int id;
public uint genderid;
public string lastname { get; set; }
}
Your question is not clear, the code work without any problem :
namespace WindowsFormsApp1
{
public class m_genders
{
public int id;
public string title;
}
public class m_employees
{
public int employeeid { get; set; }
public int genderid { get; set; }
public string lastname { get; set; }
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
List<m_genders> genders = new List<m_genders>
{
new m_genders {id = 1, title = "Male"},
new m_genders {id = 2, title = "Female"}
};
List<m_employees> Items = new List<m_employees>
{
new m_employees{ employeeid = 1, lastname = "mike", genderid = 1 },
new m_employees{ employeeid = 2, lastname = "jeni", genderid = 2 }
};
var x = from emp in Items
join sex in genders
on emp.genderid equals sex.id
into a
from b in a.DefaultIfEmpty(new m_genders())
select new
{
emp.lastname,
emp.genderid,
sex = b.title
};
}
}
}
I am trying to order a List of Entities that contains another list of Entities. I have implemented IComparable for all entities and still get the exception. All of the examples I have seen address the issue where you have one list and you order by a given field in that list but not where you have a list of lists. This issue is happening for Linq to Objects per below and also for Linq to Entities. What am I missing?
[TestClass]
public class OrderBy
{
[TestMethod]
public void OrderByTest()
{
var hobbies = new Collection<Hobby> { new Hobby { HobbyId = 1, Name = "Eating" }, new Hobby() { HobbyId = 2, Name = "Breathing" } };
var p1 = new Person
{
PersonId = 1,
Name = "A",
PersonHobbies = new Collection<PersonHobby> { new PersonHobby() { PersonHobbyId = 1}}
};
var p2 = new Person
{
PersonId = 2,
Name = "Z",
PersonHobbies = new Collection<PersonHobby> { new PersonHobby() { PersonHobbyId = 2 }}
};
var people = new List<Person> { p1, p2 };
var pplEnumerable = people.AsEnumerable();
pplEnumerable = pplEnumerable.OrderByDescending(r => r.PersonHobbies.OrderByDescending(p => p.Hobby.Name));
foreach (var person in pplEnumerable)
{
Console.WriteLine(person.Name);
}
}
public class Person : IComparable
{
public int PersonId { get; set; }
public string Name { get; set; }
public virtual ICollection<PersonHobby> PersonHobbies { get; set; }
public int CompareTo(object obj)
{
if (obj == null) return 1;
var otherPerson = obj as Person;
return PersonId.CompareTo(otherPerson.PersonId);
}
}
public class PersonHobby : IComparable
{
public int PersonHobbyId { get; set; }
public int HobbyId { get; set; }
public virtual Person Person{ get; set; }
public int PersonId { get; set; }
public virtual Hobby Hobby { get; set; }
public int CompareTo(object obj)
{
if (obj == null) return 1;
var otherPersonHobby = obj as PersonHobby;
return PersonHobbyId.CompareTo(otherPersonHobby.PersonHobbyId);
}
}
public class Hobby : IComparable
{
public int HobbyId { get; set; }
public string Name { get; set; }
public int CompareTo(object obj)
{
if (obj == null) return 1;
var otherHobby = obj as Hobby;
return HobbyId.CompareTo(otherHobby.HobbyId);
}
}
}
You cannot apply ordering to lists by default. You need to write up a custom class (sort of EquatableList etc.) or use LINQ Except & Intersect operators to compare lists.
But based on your comment, if you're looking for the LINQ equivalent of:
select * from Person p join PersonHobby ph
on ph.PersonId = p.PersonId join Hobby h
on h.HobbyId = ph.HobbyId order by h.Name
then that can be achieved as:
var query = people.SelectMany(p => p.PersonHobbies)
.Join(hobbies, ph => ph.HobbyId, h => h.HobbyId,
(ph, h) => new
{
Person = ph.Person, PersonHobby = ph, Hobby = h
})
.OrderBy(r => r.Hobby.Name);
basically we join person, person hobbies and hobby on the keys, and project all columns and sort it by the hobby.name field, as mentioned in your SQL.
I got two classes, like:
public class Person
{
public long Id { get; set; }
public string Name { get; set; }
}
public class Vampire
{
public long Id { get; set; }
}
Then, I have two lists, a list of persons and a list of vampires. All vampires are persons.
What I need is two children lists of persons, infected and notInfected. I'm building the two lists with a for, but I know it's possible using linq or something.
Any help?
Something like this:
var vampireIds = new HashSet<long>(vampireList.Select(x => x.Id));
var infectedPersons = personList.Where(x => vampireIds.Contains(x.Id));
var regularPersons = personList.Where(x => !vampireIds.Contains(x.Id));
I would go with something like the following:
void Main()
{
var list = new List<Person>(){ new Person(){ Id = 1 }, new Vampire(){ Id = 2 } };
var infected = list.Where (x => x is Vampire);
var notInfected = list.Except(infected);
}
public class Person
{
public long Id { get; set; }
public string Name { get; set; }
}
public class Vampire : Person
{
}
If only a person can be a Vapire, you could inherit Vampire from Person and then iterate through all persons and see if they are Vampires; if yes -> add to Vampire list, otherwise to non-Vampire list.
Try this:
var people = new List<Person>
{
new Person {Id = 1, Name = "John"},
new Person {Name = "Dave", Id = 2},
new Person {Id = 3, Name = "Sarah"}
};
var vamps = new List<Vampire> {new Vampire {Id = 1}};
var theInfected = people.Where(p => vamps.Select(v => v.Id).Contains(p.Id));
var theAfraid = people.Except(theInfected);
foreach (var person in theInfected)
{
System.Console.WriteLine(person.Name + " Is Infected!");
}
foreach (var person in theAfraid)
{
System.Console.WriteLine(person.Name + " Is Afraid!");
}
Hope it's helpful.