Linq AND for each item in list - c#

I have a List of ints. I need to select elements from a data source where a particular field/column matches each int in the list.
Data Source Example
ItemID ListID
1 1
1 2
2 1
I want to find all Items that match all ListIDs from a List containing List IDs 1 and 2.
Currently I'm using...
List<Item> items = (from element in MyItems where listIDs.Contains(element.ListID) select element).ToList();
However, this produces an OR query and not an AND query across multiple rows for each distinct ItemID.

You can try this way :
List<Item> result = MyItems.GroupBy(o => o.ItemID)
//find group that contain all listIDs
.Where(o => !listIDs.Except(o.Select(x => x.ListID)).Any())
//flatten groups to items
.SelectMany(o => o)
.ToList();
Related question : Determine if a sequence contains all elements of another sequence using Linq

If you are trying to compare two list for equality, then you could use SequenceEqual method.
Something along the lines
list<item> results = (from element in MyItems where listIDs.SequenceEqauls(element.ListID) select element).ToList();
I am not entirely sure if I understood your question properly. When you say "particular field/column," is that field/column some kind of collection as well?

if i got your question !! then try this
var MyItems=<your data column values>
var ItemsMatch=MyItems.Where(z=>MyIntsList.Contains(int.Pars(z.ToString()))).ToArray();

I'm not sure I understand the question. I think you have a list and you are trying to match rows that have both ListID & ItemID equal to ANY item in the list. If thats what you are sking this this is a way to do it:
List<Item> items = from element in MyItems
where listIDs.Contains(element.ListID) and listIDs.Contains(element.ItemID)
Or perhaps you are trying to match rows that have both ListID & ItemID equal to the SAME item in the list. If thats what you are sking this this is a way to do it:
List<Item> items = from element in MyItems
where listIDs.Contains(element.ListID) and element.ListID == element.ItemID

If i understood you correctly,this will do:
var result = (from item in MyItems
from i in listIDs
where i == item.ListId
select item).ToList();
It will get all Item objects in MyItems list that have ListId present in ListId.

Related

sorting by using linq comparing two lists?

I have 2 list of items;
IEnumerable<Investigator> investigators = RepositoryContext.InvestigatorRep.GetInvestigators(site.Site.Id, out totalCount);
var NewInvestigators = base.ActivePage.Investigators;
I have 30 items in investigators and 20 items in NewInvesigators, both have property Id, InvId I need to match that.
var all = investigators.Where(b => crInvestigators.Any(a => a.InvestigatorId == b.Id));
I tried this but not worked
I want to create a new list based on matching Id of those two lists. If Id matches get the particular investigator(basically a sort on investigators based on Id existing in NewInvesigators).
I can do it by using for each, but I want to know whether it is possible with linq?
in newinvestigator I have object which is having two property, investigatorId and Name.
In Investigator I have property Id , City , country.
no Name or investigatorId in the investigator list.
You could try something like this:
var result = investigators.Where(inv=>NewInvestigators.Any(ninv=>ninv.id == inv.investigatorId))
.OrderBy(inv=>inv.id);
Another way to get the same result is using a join.
var result = from inv in investigators
join ninv in NewInvestigators
on inv.id equals ninv.investigatorId
order by inv.id
select inv;

Filtering on projected property field in LINQ to entities query

The following LINQ to Entities query, a sub-query is performed and its results projected to MyViewModel.
I am looking to obtain all ProjectedModel objects with the myText string variable in the Text property of the SubModel.
var items = (from t1 in db.MyTable
select new MyModel
{
Id = t1.MyId,
SomeItems = (from s1 in db.MyOtherTable
where s1.LinkedId == t1.Id
select new SubModel
{
Id = s1.Id,
Text = s1.Text
})
}).ToList();
Pseudo code would look like:
string myText = "abc";
items = items where SomeItems.Text contains myText
If you want to get all of the items where Any of the sub items have the given text, then that's easy enough to write:
items = items.Where(item =>
item.SomeItems.Any(subItem => subItem.Text.Contains(myText)));
If you want All of the items to match, then use All. As it is, your requirements are currently incomplete as they assume there is only one sub-item. (If you know there will always be exactly one sub-item then don't make SubItems a collection, make it a single item, and get the first item in the query.)
you can do it like this way
Updated code
item.Where(w => myText.Contains(w.Text));
or you can use .StartsWith() or .EndsWith()
reference : LIKE
My answer is outdated or it may not help you but some more things which may help you
var selectItedm = (from a in item
where SqlMethods.Like(a.Text,"%"+myText+"%")
select new {a.Id,a.Text}).ToList();
you can use many more SqlMethods just include System.Data.Linq.SqlClient; reference

Getting records in between two records using Linq

I have a list of objects and need to get the list of records from this list. like I have of Countries and I need to get the list of countries which are in between country with name "Australia" and country "Indonasia", the list will not be sorted.
Am using c#.
I tried to use something like, get the index of first and second and then use that to get the list with a for loop, but would be handy if it can be done in single query.
If you do the following:
var elementsBetween = allElements
.SkipWhile(c => c.Name != "Australia")
.Skip(1) // otherwise we'd get Australia too
.TakeWhile(c => c.Name != "Indonasia");
you'll get the result you want without iterating through the list 3 times.
(This is assuming your countries are e.g. Country items with a Name string property.)
Note that this doesn't sort the countries at all - it's unclear from your question whether you want this or not but it's trivial to add an OrderBy before the SkipWhile.
this should do the job
var query = data.SkipWhile(x => x != "Australia").TakeWhile(x => x != "Indonesia")

How to select common items

Work on C# linq.I have a list to list.From this list I want to get the common items
List<SQLFrameWorkTableEntity> oParent = new List<SQLFrameWorkTableEntity>();
List<List<SQLFrameWorkTableEntity>> oChild = new List<List<SQLFrameWorkTableEntity>>();
oListParentTable = oList.Where(p => p.Parent == true).ToList();
foreach (SQLFrameWorkEntity item in oListParentTable)
{
oChild.Add(GetTableSchemaList(item, oParent));
}
Above picture describe how my oChild is.
Now this oChild is the list of list SQLFrameWorkTableEntity.I want to get the common items from the oChild.How to get it?If have any query plz ask.Thanks in advance
After replace List to List> ,I write the bellow linq syntax
var r=oChild.Select(p => p.Select(x => p.Any(y => y.ColumnName == x.ColumnName))).ToList();
Here, in r i get all list item are true,that means i fail to compare with list to list.Help me to correction this syntax.Thanks
So you want to find the items that occur in all lists produced by GetTableSchemaList(item, oParent)? Let's assume yes.
First add Distinct() (if one list is not distinct yet):
oChild.Add(GetTableSchemaList(item, oParent).Distinct());
Then after the foreach do:
var count = oListParentTable.Count;
var r = oChild.SelectMany(i => i).GroupBy(i => i)
.Where(g => g.Count() == count).SelectMany(i => i).Distinct();
The idea is that "common items" should occur exactly, say, 4 times in the flattened list of lists (SelectMany) when the number of distinct lists in oChild is 4.

LINQ to SQL Query Against Bridge Table

I'm having problems with a LINQ to SQL query in the following scenario:
I have items that have "Tags" applied via a bridge table.
I'm trying to filter a list of items to a subset that contain all of a specified set of tags and return the filtered list of items as the query result.
Tables Involved:
Item (ItemId, Name, ...other fields)
Tag (TagId, TagName)
Item_Tag(ItemId, TagId)
As an example if I had a list of Items with tags:
Item1 w/ (Tag1, Tag2)
Item2 w/ (Tag1, Tag2)
Item3 w/ (Tag1)
and I wanted to get all items where the item has both Tag1 AND Tag2 where the filter requirement is provided as an int[] of the required tagIds.
Assuming the Item and Tag Id's match the number at the end of the name. The filter for this example would be:
int[] tagFilterConditions = int[2]{1, 2};
var query = from i in itemList
//define filter here
where the result would be:
Item1,Item2 (excludes Item 3 b/c it isn't tagged with Tag1 AND Tag2)
I'm having a tough time figuring out how to combine these tables to apply that filter on the source list, I've tried using a predicate builder and various joins but just can't get the correct results.
Thanks, for any help...
// Query for all the items in the list
int[] itemIds = itemList.Select(item => item.ItemId).AsArray();
var query =
db.Item.Where(item =>
itemIds.Contains(item.ItemId));
// Apply each tag condition
foreach (int tagid in tagFilterConditions)
{
int temp = tagid;
query = query.Where(item =>
db.Item_Tag.Exists(item_tag =>
item_tag.ItemId == item.ItemId && item_tag.TagId == temp)));
}
I think the answer to your question is in .Contains(): http://blog.wekeroad.com/2008/02/27/creating-in-queries-with-linq-to-sql
Here's what I think is the relevant snippet from that site to your question:
int[] productList = new int[] { 1, 2, 3, 4 };
var myProducts = from p in db.Products
where productList.Contains(p.ProductID)
select p;
Hope this helps!
Here is some sql.
and here is the LinqToSql..
Got the following query to work using an anonymous type after defining the proper foreign key relationships the query was adapted from an answer on this question.
//the tagId's that the item in itemList must have
int[] tagFilterConditions = int[2]{1, 2};
var query =
itemList.Select( i=> new { i, itemTags= item.Item_Tags.Select(it=> it.TagId)})
.Where( x=> tagFilterConditions.All( t=> x.itemTags.Contains(t)))
.Select(x=> x.s);

Categories

Resources