How to select common items - c#

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.

Related

How find all the items of a list which are not in a generic list with multiple condition

I have a list "A" and a generic list "B". I need to find all the items of "A" those are not in "B" with multiple condition.
List "A":
EXWORK
CENTAGES
PREMIUM
List "B":
PARTICULARS CATAGORY DETAIL
EXWORK ERECTION ABC
CENTAGES ERECTION ABC
PREMIUM SUPPLY ABC
For this I use following code:
var value = A.Where(a => B.All(b => b.CATAGORY == "SUPPLY" && b.PARTICULARS!=a));
but this return the value "Premium" also whereas it shouldn't be. I am not figuring out where I am making mistake.
My Desired result is:
EXWORK
CENTAGES
Do you need to find all items in A that are not listed as a PARTICULAR categorized as SUPPLY in B?
If so, you could find all items in B where CATEGORY = "SUPPLY" and return list A except the PARTICULAR values of the filtered B items.
var value = A.Except(
B.Where(b => b.CATAGORY == "SUPPLY")
.Select(b => b.PARTICULARS));
Example fiddle here.
I think perhaps you mean:
var value = A.Where(a => !B.Any(b => b.CATAGORY == "SUPPLY" && b.PARTICULARS == a));
If you look at your query, you are trying to filter list A based on the condition from List B i.e b.CATAGORY == "SUPPLY" and PARTICULARS should be present in A list.
To get desire output, you have iterate though List B and filter records based on condition b.CATAGORY == "SUPPLY" and PARTICULARS property,
var result = B
.Where(x => x.CATAGORY == "ERECTION" && A.Contains(x.PARTICULARS)) //Use Contains.
.Select(x => x.PARTICULARS); //Select only PARTICULARS value.
Try Online
If you want data from List A, then you can break your linq in two steps,
var resultB = B
.Where(x => x.CATAGORY == "SUPPLY")
.Select(x => x.PARTICULARS).ToList();
var value = A.Except(resultB);

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

Use LINQ to group multiple columns & split data into several lists

Recently I have a task which need to do as following description, my question is that is LINQ capable to do it?
Say I have a set of data, each consists of three columns: a(int),b(int),c(int)
What I want to do is to group these data by a and b, and for each distinct pair (a,b), store their corresponding c into separate list.
For example: If I have a set of data(a,b,c) {(1,3,5), (2,4,6), (1,3,7), (2,4,8)},
I want to split the data into two separate list, each contains c's value:
List 1 (a=1,b=3) : [5,7]
List 2 (a=2,b=4) : [6,8]
What I have tried is to group / order by the data by (a,b), and got a sorted list of data, I can of course use any loop to iterate the set of data and split them into several list, just wondering if there is a more beautiful solution, like using a single LINQ query?
Any suggetion is pleased! Thanks :)
Try this:
var result = data.GroupBy(x => new { x.a, x.b })
.Select(g => Tuple.Create
(
new List<int> { g.Key.a, g.Key.b },
new List<int>(g.Select(x => x.c))
)).ToList();
Here's the query expression equivalent:
var result = (from x in data
group x by new { x.a, x.b } into g
select Tuple.Create(
new List<int> { g.Key.a, g.Key.b },
new List<int>(g.Select(x => x.c)))).ToList();

Linq AND for each item in list

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.

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

Categories

Resources