NOT IN for LINQ? - c#

Is there a way for me to filter Employees by group:
ex:
List<String> notInGroups = GetNotInGroups();
var list = from p in employees
where p.Group.Name notin(notInGroups)
select p;
Is there some way to do something like this?
Thanks

You can do !Contains, like:
var list = from p in employees
where !notInGroups.Contains(p.Group.Name)
select p;

Not able to test, but won't something like this work?
var notInGroups = GetNotInGroups();
var list = from p in employees
where notInGroups.Contains(p.Group.Name) == false
select p;

Try where !notInGroups.Contains(p.Group.Name); as your WHERE clause.

List is not particularly well suited for the task of searching through the collection to see if it contains a particular item, which is exactly what you want to do. While writing the code is easy enough (there are already a lot of answers showing how) you will benefit noticeably from using a more appropriate data structure that can be more efficiently searched, such as a HashSet:
var notInGroups = new HashSet<string>(GetNotInGroups());
var list = from p in employees
where !notInGroups.Contains(p.Group.Name)
select p;

You can do something like this..
List<String> notInGroups = GetNotInGroups();
var list = from p in employees
where !(notInGroups.Contains(p.Group.Name))
select p;

Related

c# store two vars objects in one var object

In the past, i was reading data from one excel sheet named "On leave" and do operation on the result like this:
var resultNew1 = (from x in dataNew.Worksheet<Employee>("On Leave")
select x).ToList();
but now I have got another sheet which is "Working". so I did this:
var resultNew1 = (from x in dataNew.Worksheet<Employee>("On Leave")
select x);
var resultNew2 = (from x in dataNew.Worksheet<Employee>("Working")
select x);
please notice that the first one was ToList()
but now I didn't make ToLists() because I want to ask you if there is a way to store these two vars which are resultsNew1 and resultsNew2 in one var and then make that var ToList()
If you need more infomration, please tell me
You can use Concat
var employees = dataNew.Worksheet<Employee>("On Leave")
.Concat(dataNew.Worksheet<Employee>("Working"))
.ToList();
You can use List<T>.AddRange:
List<Employee> employees = new List<Employee>();
employees.AddRange(resultNew1);
employees.AddRange(resultNew2);

How do I select the top ten scores in a database table full of scores using linq in C#

I'm new to Linq and database programming in general, I could really use some help.
I have tried using
var TopTen = from t in datacontext.Scores.Take(10)
orderby t.LifetimeScore descending
select t;
but this only seems to give me the first ten entries in the DB not the top ten. I know I need to order the table before the search but I just can't figure it out.
Thanks, any help is appreciated
You have to take 10 from the result, not before:
var TopTen = (from t in datacontext.Scores
orderby t.LifetimeScore descending
select t).Take(10);
var TopTen = datacontext.Scores.OrderByDescending(t => LifetimeScore ).Take(10)
I'm new to LINQ myself but here's what I think should work:
var TopTen = (from t in datacontext.Scores
orderby t.LifetimeScore descending
select t).Take(10);
var TopTen = from t in datacontext.Scores
orderby t.LifetimeScore descending
select t;
TopTen = TopTen.Take(10).ToArray();
Last statement will make sure the query is executed.

Entity framework with "Group By" and/or "Order by"

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();

Linq to SQL: DataTable.Rows[0]["ColumnName"] equivalent

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");

LINQ Query to Return multiple results

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.

Categories

Resources