Entity Framework select distinct name - c#

How can I do this SQL query with Entity Framework?
SELECT DISTINCT NAME FROM TestAddresses

Using lambda expression..
var result = EFContext.TestAddresses.Select(m => m.Name).Distinct();
Another variation using where,
var result = EFContext.TestAddresses
.Where(a => a.age > 10)//if you have any condition
.Select(m => m.name).Distinct();
Another variation using sql like syntax
var result = (from recordset
in EFContext.TestAddresses
.where(a => a.city = 'NY')//if you have any condition
.select new
{
recordset.name
}).Distinct();

Try this:
var results = (from ta in context.TestAddresses
select ta.Name).Distinct();
This will give you an IEnumerable<string> - you can call .ToList() on it to get a List<string>.

The way that #alliswell showed is completely valid, and there's another way! :)
var result = EFContext.TestAddresses
.GroupBy(ta => ta.Name)
.Select(ta => ta.Key);
I hope it'll be useful to someone.

DBContext.TestAddresses.Select(m => m.NAME).Distinct();
if you have multiple column do like this:
DBContext.TestAddresses.Select(m => new {m.NAME, m.ID}).Distinct();
In this example no duplicate CategoryId and no CategoryName i hope this will help you

Entity-Framework Select Distinct Name:
Suppose if you are using Views in which you are using multiple tables and you want to apply distinct in that case first you have to store value in variable & then you can apply Distinct on that variable like this one....
public List<Item_Img_Sal_VIEW> GetItemDescription(int ItemNo)
{
var Result= db.Item_Img_Sal_VIEW.Where(p => p.ItemID == ItemNo).ToList();
return Result.Distinct().ToList();
}
Or you can try this Simple Example
Public Function GetUniqueLocation() As List(Of Integer)
Return db.LoginUsers.Select(Function(p) p.LocID).Distinct().ToList()
End Function

use Select().Distinct()
for example
DBContext db = new DBContext();
var data= db.User_Food_UserIntakeFood .Select( ).Distinct();

In order to avoid ORDER BY items must appear in the select list if SELECT DISTINCT error, the best should be
var results = (
from ta in DBContext.TestAddresses
select ta.Name
)
.Distinct()
.OrderBy( x => 1);

Entity-Framework Select Distinct Name:
Suppose if you are want every first data of particular column of each group ;
var data = objDb.TableName.GroupBy(dt => dt.ColumnName).Select(dt => new { dt.Key }).ToList();
foreach (var item in data)
{
var data2= objDb.TableName.Where(dt=>dt.ColumnName==item.Key).Select(dt=>new {dt.SelectYourColumn}).Distinct().FirstOrDefault();
//Eg.
{
ListBox1.Items.Add(data2.ColumnName);
}
}

Related

Write query in Entity Framework

I have a query which I ran successfully in SQL Server Management Studio, which returns the table values shown in the screenshot
The query I used is:
SELECT tcoid, COUNT(*) ownleasetank
FROM TankProfile
WHERE ownleasetank = 3
GROUP BY tcoid
Now I'm using Entity Framework to make things easier in my sample project.
I used this method to return the table values as array object:
public async Task<Object> GetLeaseInformationPrincipal()
{
ISOTMSEntities context = new ISOTMSEntities();
var testleaseinfo = from d in context.TankProfiles
join f in context.TankOperators
on d.tcoid equals f.tcoId
where (d.ownleasetank == 3)
select new { f.tcoName, d.ownleasetank } into x
group x by new { x.tcoName } into g
select new
{
tconame = g.Key.tcoName,
ownleasetank = g.Select(x => x.ownleasetank).Count()
};
return testleaseinfo.ToList();
}
but it is not working properly. I also tried other ways, when I use where and groupby method in Entity Framework it doesn't working properly for me.
Does anybody know the solution for this?
It's very simple with LINQ methods:
context.TankProfiles
.Where(t => t.ownleasetank = 3)
.GroupBy(t => t.tcoid)
.Select(g => new {g.Key, g.Count()})
.ToArray();
I have no idea why in your C# version of the query you have such opeartions such join, while your SQL query is very simple. You have to rethink that :)
var c = from t in context.TankProfile
where t.ownleasetank == 3
group t by t.tcoid into g
select new { tcoid=g.Key, ownleasetank=g.Select(x => x.ownleasetank).Count() };
return c.ToList();

SQL to LINQ expres

I'm trying to convert a SQL expression to Linq but I can't make it work, does anyone help?
SELECT
COUNT(descricaoFamiliaNovo) as quantidades
FROM VeiculoComSeminovo
group by descricaoFamiliaNovo
I try this:
ViewBag.familiasCount = db.VeiculoComSeminovo.GroupBy(a => a.descricaoFamiliaNovo).Count();
I need to know how many times each value repeats, but this way it shows me how many distinct values ​​there are in the column.
You can try:
var list = from a in db.VeiculoComSeminovo
group a by a.descricaoFamiliaNovo into g
select new ViewBag{
familiasCount=g.Count()
};
or
var list = db.VeiculoComSeminovo.GroupBy(a => a.descricaoFamiliaNovo)
.Select (g => new ViewBag
{
familiasCount=g.Count()
});
If you need column value:
new ViewBag{
FieldName=g.Key,
familiasCount=g.Count()
};
You don't need the GROUP BY unless there are fields other than the one in COUNT. Try
SELECT
COUNT(descricaoFamiliaNovo) as quantidades
FROM VeiculoComSeminovo
UPDATE, from your comment:
SELECT
COUNT(descricaoFamiliaNovo) as quantidades,
descricaoFamiliaNovo
FROM VeiculoComSeminovo
GROUP BY descricaoFamiliaNovo
That's it as SQL. In LINQ it is something like:
var reponse = db.VeiculoComSeminovo.GroupBy(a => a.descricaoFamiliaNovo)
.Select ( n => new
{Name = n.key,
Count = n.Count()
}
)
Not tested.
Ty all for the help.
I solved the problem using this lines:
// get the objects on db
var list = db.VeiculoComSeminovo.ToList();
// lists to recive data
List<int> totaisFamilia = new List<int>();
List<int> totaisFamiliaComSN = new List<int>();
// loop to cycle through objects and add the values ​​I need to their lists
foreach (var item in ViewBag.familias)
{
totaisFamilia.Add(list.Count(a => a.descricaoFamiliaNovo == item && a.valorSeminovo == null));
totaisFamiliaComSN.Add(list.Count(a => a.descricaoFamiliaNovo == item && a.valorSeminovo != null));
}
The query was a little slow than I expected, but I got the data

Distinct method does not work Entity Framework

How do I get randomly similar data
me tried to merge different ones in the first stage but Different function does not work,
var turler= (from x in db.bird_table_ad
join e in db.kus_resim on x.tr_x equals e.kus_tur
where x.aile == item
select new GozlemTurleri
{
id = x.id,
kod = x.kod,
tr_x = x.tr_x,
en_x = x.en_x,
lt_x = x.lt_x,
turfotourl="image_resize.phpad="+e.altDIR+"/"+e.resim+"&yon="+(e.galeri=="fg"?"2":"HD2"),
aile = x.aile,
gfoto = x.gfoto
}).Distinct().ToList();
If you try to get distinct record with regarding to tr_x from database then you can use GroupBy in entity framework.
So your code will be.
.GroupBy(x => x.tr_x).Select(x => x.First()).ToList();
Instead of
.Distinct().ToList();

How to match a list of item to database in C#

I have a list of string
List<string> list = new List<string>();
list.Add("john");
list.Add("David");
list.Add("Sam");
Now I want to check whether my column in database contains these list Items.
var v = db.employee.where(s => s.Content.Contains(list));
My question is how can I match all list items to database column in just one query without using any loop. The query must return result if single list item is matched with column. The query I mentioned above not working. Please help me to solve this.
This will only work with the assumption that your db is an Entity Framework DbContext and that s.Content is a string. If you're using some other ORM then it may not work.
List<string> list = new List<string>();
list.Add("john");
list.Add("David");
list.Add("Sam");
var v = db.employee.Where(s => list.Contains(s.Content)).ToList();
You can do this:
List<string> list = new List<string>();
list.Add("john");
list.Add("David");
list.Add("Sam");
var v = db.employee
.ToList()
// This filtering doesn't happen in your SQL server.
.Where(s => list.Any(x => s.Content.Contains(x)));
You can try to omit .ToList() line but I'm afraid your ORM will not know how to convert the query to SQL.
If you want the whole query to be executed in SQL you should consider building the query this way:
var query = db.employee.AsQueryable();
query = list.Aggregate(query,
(query, name) => query.Where(empl => empl.Content.Contains(name)));
what about:
List<string> list = new List<string> {"john", "Warwick", "Sam"};
var vresult = _db.employee.Where(x => list.Contains(x.Content)).ToList();
please indicate what you are expecting...? like how is it not working?
If return is different than null, exists.
public List<Employee> CheckIfExists(List<string> nameList)
{
if (nameList == null)
{
return null;
}
string inClause = "";
foreach (var item in nameList)
{
inClause = string.Format("{0},{1}", inClause, item);
}
return db.employee.SqlQuery("SELECT * FROM employee WHERE employee.Name IN (#p0)", inClause).ToList();
}
Each element of list will be passed as an argument to s.Content.Contains
and here s is an employee record.
var v = db.employee.Where(s => list.Any(s.Content.Contains));
This might help you,
list with name= {"john", "David", "Sam"}
you want to check if John/David/Sam exists in the employee table.
The below query is to check if the particular name exists in employee or not
var _data = _db.employee.Where(emp => list.Any(li => li.name == emp.name)).ToList();
LINQ in query syntax:
var result = from o in db.employee
where list.Contains(o.Content)
select o;

IN Operator in where clause

List<HelprClass.Organizer> org =
( from EventOrg in cntx.EventOrganizer
from MstrOrg in cntx.Organizer
where EventOrg.OrganizerID == MstrOrg.OrganizerID
Select new HelprClass.Organizer
{
OrganizerName = MstrOrg.OrganizerName
}).ToList()
This work fine now i want to use IN Opeartor in the above Query.
in the EventOrganizer I have EventID now i want to select only Event ID exsist in EventOrganizer collection
I have EventID another var varibale
Var EventID= From EvntID in Evetn Select new {ID= EvntID.EventID};
Something like this
where
EventOrg.OrganizerID == MstrOrg.OrganizerID
&& EventOrg.EventID in EventID.ID
How I can achive this ?
I will appreciate your help
Try this:
var EventIDs = from EvntID in Event select EvntID.EventID;
var org = (from EventOrg in cntx.EventOrganizer
from MstrOrg in cntx.Organizer
where EventOrg.OrganizerID == MstrOrg.OrganizerID
select new {E=EventOrg, M=MstrOrg}
).ToList();
org = org
.Where(o => EventIDs.Contains(o.E.EventID) )
.Select(o => new HelprClass.Organizer
{
OrganizerName = o.M.OrganizerName
}
);
If you are using Entity Framework you can not use a Contains statement, which would be an easy solution in Linq. SO if it's just Linq 2 Entities, use a where clause like "where EventId.Contains(EventOrg.Id)"
If you are indeed using Entity Framework you will have to build an or expression based on the Id's in the EventID Collection.

Categories

Resources