Consider this:
var query = from r in this._db.Recipes
where r.RecipesID == recipeID
select new { r.RecipesID, r.RecipesName };
How would i get individual columns in my query object without using a for-loop?
Basicly: how do I translate DataTable.Rows[0]["ColumnName"] into Linq syntax?
It's really unclear what you are looking for, as your two samples are compatible.
As close as I can figure, what you want is:
var rows = query.ToList();
string name = rows[0].RecipesName;
string name = this._db.Recipes.Single(r => r.RecipesID == recipeID).RecipesName;
This is the way to go about it:
DataContext dc = new DataContext();
var recipe = (from r in dc.Recipes
where r.RecipesID == 1
select r).FirstOrDefault();
if (recipe != null)
{
id = recipe.RecipesID;
name = recipe.RecipesName;
}
Sorry, misunderstood your question. As others are saying, you can use ToList() to get a List back. An alternative if all you need is the first one, just use:
query.First().ColumnName
or if you want to avoid an exception on empty list:
var obj = query.FirstOrDefault();
if (obj != null)
obj.ColumnName;
Original Answer (so the comment makes sense):
Use Linq to Datasets. Basically would be something like:
var query = from r in yourTable.AsEnumerable()
select r.Field<string>("ColumnName");
Related
I've got a table Installation which can contains one or many Equipements.
And for functionnal reasons, I've overwritten my table Installation and added a field NbrEquipements.
I want to fill this field with Linq, but I'm stuck...
Due to special reasons, there is no relation between these to tables. So, no Installation.Equipements member into my class. Therefore, no Installation.Equipements.Count...
I'm trying some stuff. Here is my code:
var query = RepoInstallation.AsQueryable();
// Some filter
query = query.Where(i => i.City.RegionId == pRegionId));
int?[] etatIds = { 2, 3 };
query = (from i in query
select new Installation
{
NbrEquipements= (from e in RepoEquipement.AsQueryable()
where e.InstallationSpecialId == i.SpecialId
&& (etatIds.Contains(e.EquEtat))
select e.SasId
).Count()
});
But with this try, I got this error:
The entity or complex type 'myModel.Installation' cannot be constructed in a LINQ to Entities query
I've tried some other stuff but I'm always turning around...
Another thing that can be useful for me: It would be great to fill a field called Equipements which is a List<Equipement>.
After that, I would be able to Count this list...
Is it possible ?
Tell me if I'm not clear.
Thanks in advance.
Here is the final code:
//In the class:
[Dependency]
public MyEntities MyEntities { get; set; }
//My Methode code:
var query = MyEntities .SasInstallations.AsQueryable();
// Some filter
query = query.Where(i => i.City.RegionId == pRegionId));
var liste = new List<Installation>();
var queryWithListEquipements =
from i in query
select new
{
Ins = i,
EquipementsTemp = (from eq in MyEntities.Equipements.AsQueryable()
where eq.SpecialId == i.SpecialId
&& (etatIds.Contains(eq.SasEquEtat))
select eq
).ToList()
};
var listWithListEquipements = queryWithListEquipements.ToList();
foreach (var anonymousItem in listWithListEquipements)
{
var ins = anonymousItem.Ins;
ins.Equipements = anonymousItem.EquipementsTemp;
ins.NumberEquipements = ins.Equipements.Count();
liste.Add(ins);
}
return liste;
By the way, this is very very fast (even the listing of Equipements). So this is working exactly has I wished. Thanks again for your help everyone!
Use an anonymous type. EF does not like to instantiate entity classes inside a query.
var results = (from i in query
select new
{
NbrEquipements= (from e in RepoEquipement
where e.InstallationSpecialId == i.SpecialId
&& (etatIds.Contains(e.EquEtat))
select e.SasId
).Count()
})
.ToList();
Notice how I used select new instead of select new Installation.
You can then use the data inside the list (which is now in memory) to create instances of type Installation if you want like this:
var installations = results.Select(x =>
new Installation
{
NbrEquipements = x.NbrEquipements
}).ToList();
Here is how to obtain the list of equipment for each installation entity:
var results = (from i in query
select new
{
Installation = i,
Equipment = (from e in RepoEquipement
where e.InstallationSpecialId == i.SpecialId
&& (etatIds.Contains(e.EquEtat))
select e).ToList()
})
.ToList();
This will return a list of anonymous objects. Each object will contain a property called Installation and another property called Equipment (which is a list). You can easily convert this list (of anonymous objects) to another list of whatever type that you want.
I have this simple query:
SELECT xObjectID, xObjectName
FROM dbo.xObject
where CONTAINS( xObjectRef, '1838 AND 238671')
Which i am trying to convert to linq but i can't get it to work,
And it's driving me up the wall.
Thanks!
Fulltext searches are not compatible with linq to sql. You will have to call a stored procedure.
Edit:
Or do you want a linq query that will return the same result set as the sql?
Does this work for you? This does require xObjectRef to be a property of xObject.
from obj in dbo.xObject
where obj.xObjectRef.Contains("1838") && obj.xObjectRef.Contains("238671")
select new { xObjectId = obj.xObjectId, xObjectName = obj.xObjectName}
var query = from c in context.xObject
where c.xObjectRef.Contains("1838") && c.xObjectRef.Contains("238671")
select new { ObjectID = c.xObjectID, ObjectName = c.xObjectName };
var a = xObject.where(n=>n.Contains("1838") && n.Contains("238671") )).
Select(s=>new {xObjectID=s.xObjectID , xObjectName=s.xObjectName});
I have linq query as follows:
var result = (from Customer cust in db select new { userNameList = cust.UserName }).ToList();
i want to loop through each value in the list<>
I tried to use the foreach to accomplish this. It is stupid i could not figure it out
I'm using something like this
foreach (List<string> item in result)
{
if (item.ToString() == userName)
{
userExistsFlag = 1;
}
}
But the .net compiler is just freaking out:
and giving me these errors
Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List'
Cannot convert type 'AnonymousType#1' to 'System.Collections.Generic.List'
Thanks in anticipation
OF ALL THESE IMPLEMENTATIONS WHICH ONE IS MOST EFFICIENT AND CONSUMES LESS RESOURCES.
IT WOULD BE KIND ENOUGH IF SOME ONE CAN CLARIFY THIS FOR ME.
Shorter using Linq:
bool userExistsFlag = result.Any( x=> x.userNameList == userName);
As suggested in the other answers you do not need to project to an anonymous type:
var userNames = (from Customer cust in db select cust.UserName).ToList();
bool userExists = userNames.Contains(userName);
Edit:
The most efficient - if you do not need the set of user names otherwise - is to query the DB directly to check whether the user name exists, so
bool userExists = db.Any( x => x.UserName == userName);
Credit goes to #Chris Shaffer in the comments and #Cybernatet's answer - he was almost there. I would suggest you accept his answer but use Any() ;-)
Try:
var result = (from Customer cust in db select new { userNameList = cust.UserName }).ToList();
userExistsFlag = result.Where(a=> a.userNameList == userName).Count() > 0;
or
userExistsFlag = (
from Customer cust in db
where cust.UserName = userName
select cust
).Count() > 0;
If your query returns a list of names, your FOREACH loop should look like this
foreach( String name in results ){
...
}
Skip using new { userNameList = cust.UserName } which is making it an anonymous instance. You can try
var result = (from Customer cust in db select cust.UserName ).ToList();
if you're just getting the one property and want a list of strings there is no reason to use an anonymous type. code should work like this:
var result = (from Customer cust in db select cust.UserName).ToList();
Say we've got a project that allows user to download things. On the main page, I want to show the Most downloaded files ordered by the number of download! All that using EF.
How can i do this !! I've tried many things with Group By (Its a nightmare when you've got a lot of informations in an object). And i still dunno how to do this...
var query = from details in m_context.TransactionDetails
where details.Chanson != null
group details by details.Items into AnItem
orderby AnItem.Count()
select new Item() {
IdItem = Chansons.Key.IdItem,
ItemState= Chansons.Key.ItemState,
[...This object got something like 20 including links to other objects ... ]
};
Anyone have an idea?
Thanks :o)
Oh and sorry for my english, I'm giving my best but im from Quebec (Usualy talk french).
Salut!
I'm going to guess at your data model a little, here, but I don't think you need to group:
var query = from details in m_context.TransactionDetails
where details.Chanson != null
orderby details.Items.Count() descending
select new Item
{
IdItem = details.Chanson.IdItem,
ItemState= details.Chanson.ItemState,
// ...
};
Bonne chance!
Update: For albums:
var query = from details in m_context.TransactionDetails
where details.DisqueCompact != null
orderby details.Items.Count() descending
select new Item
{
IdItem = details.DisqueCompact.IdItem,
ItemState= details.DisqueCompact.QuelqueChose...
// ...
};
You probably need two queries given your data model.
For grouping data, you can read this How-To from MSDN.
This is an example of how you should do it:
//this is a entity framework objects
CTSPEntities CEntity = new CTSPEntities();
//and this is your example query
var query = (from details in CEntity.Purchase_Product_Details
group details by new { details.Product_Details.Product_Code, details.Product_Details.Product_Name} into Prod
select new
{
PID = Prod.Key.Product_Code,
PName = Prod.Key.Product_Name,
Amount = Prod.Sum(c => c.Lot_Amount),
count= Prod.Count()
}).OrderBy(x => x.Amount);
foreach (var item in query)
{
Console.WriteLine("{0},{1},{2},{3}",item.PID,item.PName,item.Amount,item.count);
}
Console.ReadLine();
I am trying to write a textbox that will search on 5 DB columns and will return every result of a given search, ex. "Red" would return: red ball, Red Williams, etc. Any examples or similar things people have tried. My example code for the search.
Thanks.
ItemMasterDataContext db = new ItemMasterDataContext();
string s = txtSearch.Text.Trim();
var q = from p in db.ITMSTs
where p.IMITD1.Contains(s) ||
p.IMITD2.Contains(s) ||
p.IMMFNO.Contains(s) ||
p.IMITNO.Contains(s) ||
p.IMVNNO.Contains(s)
select p;
lv.DataSource = q;
lv.DataBind();
"q" in your example will be an IQueryable<ITMST>. I don't think the Datasource property of WebControl know what to do with that. try writing that line as:
lv.DataSource = q.ToList();
You can do something like this (syntax may be off )
using(var db = new ItemMasterDataContext())
{
var s = txtSearch.Text.Trim();
var result = from p in db.ITMSTs select p;
if( result.Any(p=>p.IMITD1.Contains(s))
lv.DataSource = result.Where(p=>p.IMITD1.Contains(s))
else if ( result.Any(p=>p.IMITD2.Contains(s))
lv.DataSource = result.Where(p=>p.IMITD1.Contains(s))
lv.DataBind();
}
or you might want to use this Link or this Link from MSDN.
Happy Coding!!
What you have is generally what people would do using linq. If you wanted to get more complex and use database wild cards then take a look at the SqlMethods class in System.Data.Linq.
# James Curran
You can assign the DataSource property q and it will work fine. The only different is when the query gets executed.