sorting by using linq comparing two lists? - c#

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;

Related

Merg two list to get Third List both Lists Have two common and one different Column c#

I have two lists,
List <AgencyCount> Agency= AgencyList.ToList();
List<IndCount> Ind = individualList.ToList();
want to merge it into third list that is,
List<complain> list = new List<complain>();
Columns in Agency list,
CityId
CityNM
Acount
Columns in Ind list,
CityId
CityNM
Icount
Third list is using object of class type that is
CityId
CityNM
Acount
Icount
Values in the Agency and Ind list for the first two columns are same.
Resulting List get values for the first two column that is same and than get third column of both list as showns above.
Here is an example. As you said, that AgencyList and IndividualList has CityId and city_NM as common values, I'm assuming that the join of both lists are with these fields
The linq query returns an anonymous type, that you compose with fields from both lists. You can return a concrete object simply creating a new ResultClass and doing select new ReturnClass { in the linq
Updated as per #tsahi Asher comment
var qry = from a in AgencyList.ToList()
join i in individualList.ToList()
on a.CityId equals i.City_NM
select new {
a.yourField,
i.otherField
};
return qry.ToList();
#mnieto's answer was correct for the original question, which was completely rewritten (please don't do that, it leads to answers to non-existent questions like this). For the current version of the question, the answer is very similar, with only a different join condition:
var qry = from a in Agency
join i in Ind
on new { a.CityId, a.CityNM } equals new { i.CityId, i.CityNM }
select new {
a.CityId,
a.CityNM,
a.Acount,
i.Icount
};
return qry.ToList();

changing one list to another in .net

I have list e.g:
list1=
{{id=1,address=a},
{id=1,address=b},
{id=2,address=c},
{id=2,address=d}}
how can i change this list into something like
list2=
{{id=1,address={a,b}},
{id=2,address={c,d}}}
that is putting same id's list into one with inner list containing other elements
group is your friend here. Assuming the output type's address property is a List<T> something like:
var res = (from x in input
group x by x.id into grouped
select new Output {
id = grouped.Key,
address = grouped.ToList()
}).ToList();

LINQ contains between 2 lists

I have a string List and a supplier List<supplier>.
string list contains some searched items and supplier list contains a list of supplier object.
Now I need to find all the supplier names that matches with any of the items in the string List<string>.
this is one of my failed attempts..
var query = some join with the supplier table.
query = query.where(k=>stringlist.contains(k.companyname)).select (...).tolist();
any idea how to do that??
EDIT:
May be my question is not clear enough...I need to find a list of suppliers(not only names,the whole object) where suppliers names matches with the any items in the string list.
If I do
query = query.where(k=>k.companyname.contains("any_string")).select (...).tolist();
it works. but this is not my requirement.
My requirement is a list of string not a single string.
Following query will return distinct suppliers names which exist in list of names:
suppliers.Where(s => stringlist.Contains(s.CompanyName))
.Select(s => s.CompanyName) // remove if you need whole supplier object
.Distinct();
Generated SQL query will look like:
SELECT DISTINCT [t0].[FCompanyName]
FROM [dbo].[Supplier] AS [t0]
WHERE [t0].[CompanyName] IN (#p0, #p1, #p2)
BTW consider to use better names, e.g. companyNames instead of stringlist
You could use Intersect for this (for just matching names):
var suppliersInBothLists = supplierNames
.Intersect(supplierObjects.Select(s => s.CompanyName));
After your EDIT, for suppliers (not just names):
var suppliers = supplierObjects.Where(s => supplierNames.Contains(s.CompanyName));
var matches = yourList.Where(x => stringList.Contains(x.CompanyName)).Select(x => x.CompanyName).ToList();
Either use a join as Tim suggested or you could just use a HashSet directly. This is much more efficient that using .Contains on a List as in some of the other answers.
var stringSet = new HashSet(stringList);
var result = query.Where(q => stringSet.Contains(q.Name));

Splitting Linq List by grouping

for reporting purposes i wanna split a list of purchase orders into multiple lists. One list for each purchase address. I know it's possible to group the list by purchase address, but my question is how to split the list by this purchase address into multiple lists and use these multiple list to create individual reporting files.
code:
(from o in orders
group o by new {field1, field2, field3, field4} into og
orderby og.Key.field1
select new ViewClass
{
purchaseAddress = og.Key.field1,
product = og.key.field2,
count = og.count
}).ToList()
question: how to split above list into multiple lists for each purchaseAddress?
There's a built-in function that I think does what you want. If I assume that your code is assigned to a variable called query then you can write this:
ILookup<string, ViewClass> queryLists = query.ToLookup(x => x.purchaseAddress);
This essentially creates a list of lists that you access like a dictionary, except that each value is a list of zero or more values. Something like:
IEnumerable<ViewClass> someList = queryLists["Some Address"];
Just turn each group into a List.
select new ViewClass
{
purchaseAddress = og.Key.field1,
product = og.key.field2,
count = og.count,
List = og.ToList()
}).ToList();
Oh, your grouping is one way for entities and another way for pages... just regroup.
List<ViewClass> classes = (
from o in orders
group o by new {field1, field2, field3, field4} into og
orderby og.Key.field1
select new ViewClass
{
purchaseAddress = og.Key.field1,
product = og.key.field2,
count = og.count
}).ToList();
List<List<ViewClass>> regrouped = (
from c in classes
group c by c.purchaseAddress into g
select g.ToList()
).ToList();
Another simple built-in function that you can use is the GroupBy function. It does a similar job as the ToLookup but it means that your new list is IQuerable, not like a dictionary and a few other things (see this article for a good breakdown)
var newList = orders.GroupBy(x => x.field1);
This will return a list of lists grouped by the field(s) you specify.

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