T
T
Timbioz2015-10-29 11:12:32
Database
Timbioz, 2015-10-29 11:12:32

How to select different data from DB using Entity Framework?

There is a table with the repeating data on a certain key. Example:
id Name CompanyId 1
Tim 1111111 2
Jack 126555
3 Tim 1111111 4
Kris 59911919
5 Tim 1111111
6 Jonh 1111111
7 Kim 1111111
8 Clark
9984848

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Mozhaykin, 2015-10-29
@Timbioz

class Employee
{
  public int Id { get; set; }
  public string Name { get; set; }
  public int CompanyId { get; set; }
  
  public override string ToString()
  {
    return string.Format("Employee Id = {0}, Name = {1}, CompanyId = {2}", Id, Name, CompanyId);
  }
}

void Main()
{
  var employees = new Employee[] {
      new Employee() {Id = 1, Name = "Tim", CompanyId = 1111111},
      new Employee() {Id = 2, Name = "Jack", CompanyId = 126555},
      new Employee() {Id = 3, Name = "Tim", CompanyId = 1111111},
      new Employee() {Id = 4, Name = "Kris", CompanyId = 59911919},
      new Employee() {Id = 5, Name = "Tim", CompanyId = 1111111},
      new Employee() {Id = 6, Name = "John", CompanyId = 1111111},
      new Employee() {Id = 7, Name = "Kim", CompanyId = 1111111},
      new Employee() {Id = 8, Name = "Clark", CompanyId = 9984848},
  };
  
  var filtered = from emp in employees group emp by emp.CompanyId into g where g.Count() == 1 select g.FirstOrDefault();
  
  foreach (var emp in filtered)
  {
      Console.WriteLine(emp);
  }
}

D
Dmitry Kovalsky, 2015-10-29
@dmitryKovalskiy

Clumsy, but somehow

var t = from c in Table
            where (from d in Table group d by d.CompanyId into dGroup
                   where dGroup.Count() ==1
                   select dGroup.CompanyId).Contains(c.CompanyId)
           select c

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question