Getting records in between two records using Linq - c#

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

Related

Where clause using Linq - search for a list of Object

One doctor can work in One hospitals.
The Doctor table looks like this:
Id
Name
Speciality
HospitalName
HospitalName is a string.
Hospital Table contains the following
Id
HospName
Address
Now, I have a List of Hospital Objects. Where I need to filter it using a List of Doctor. I need to search from the Doctors table, where the HospitalName is equal to HospName in the Hospital table.
Code:
List<Hospital> hos = listHospitals;
var doctors = docList
.Where(h=> listHospitals.Contains(h.HospitalName));
I get an error that states :
Can not convert form string to Hospital`
How can I solve this ?
You can use Any() like below.listHospitals is of type List<Hospital> and thus you will have to query that list to compare hospital name.
List<Hospital> hos = listHospitals;
var doctors = docList
.Where(h=> listHospitals.Any(x => x.HospitalName == h.HospitalName)).ToList();
Try this...
var list = docList.Where(d => listHospitals.FirstOrDefault(h => d.HospitalName == h.HospName) != null).ToList();
I'd say to use Count() instead of Any() since a List has a .Length or .Count property thus not need to go through the GetEnumerator()/MoveNext()/Dispose() sequence required by Any().
Resulting in the following code:
List<Hospital> hos = listHospitals;
var doctors = docList
.Where(h=> hos.Count(x => x.HospitalName == h.HospitalName) > 0).ToList();

Getting null data when executing LINQ to Entities query

I have the following Book table:
From this table, I am trying to get the latest registrationNumber based on the group ID as an input from the user.
So, my query looks like this at the moment:
var booksQuery = _context.Books.Where(g => g.GroupId == id)
.OrderByDescending(g => g.RegistrationNumber).GroupBy(g => g.GroupId);
id is the group Id specified by the user. So for example, if id = 15, then I should get the 15:6 as my latest registration number. To do that, I basically grouped by id and ordered the result by descending order. But that is giving me null results. Anyone know why? I am very new to this LINQ-Entitiy coding.
As mentioned by others you really should make your registrationNumber field an integer since you are wanting to sort on it. In the event, you can't make the change, below is a Linq query that basically parses the registration number and converts to an integer to sort on the first and second part by splitting at the colon. This works for sorting when you have 15:10, etc, as in the string sort 15:6 comes before 15:10
var booksQuery = books.Where(g => g.GroupId == id).ToList();
var bookWanted = booksQuery
.OrderByDescending(g => int.Parse(g.registrationNumber.Split(':')[0]))
.ThenByDescending(g=> int.Parse(g.registrationNumber.Split(':')[1]))
.FirstOrDefault();

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;

C# List values compare and add

var bndlSummary = GetBundleSummary(GroupIds);
var cntrSummary = GetContainerSummary(GroupIds);
var finalSummary = GetFinalSummary(GroupIds);
Above var are fetching some data from Database. They all have one Common Field Name "City".
City value can be repeated many time like City = Chicago can be 3 times or more). now I want this Field City value into allCityNames. I don't want City Info to be repeated from any var.
var allCityNames = new cityAnalysisSummary();
Please help me how how should i do it. Thank you very much for your help.
bndlSummary.Select(b => b.City)
.Concat(cntrSummary.Select(c => c.City))
.Concat(finalSummary.Select(f => f.City))
.Distinct();
Use Select to get all the cities from each collection, Concat to put them all together, and Distinct to remove any duplicates.
You can also use Union which will remove duplicates while concatenating:
bndlSummary.Select(b => b.City)
.Union(cntrSummary.Select(c => c.City))
.Union(finalSummary.Select(f => f.City));

How to Group and Order in a LINQ Query

I would like to group & order by in a query builder expression. The following query gets me close to what i want but the order by does not appear to be working.
what i have is an object that has unique ids but some will have a common versionId. I would like to get the last edited item of the same versionId. So only one item per version id and i want it to be the last edited one.
IQueryable<Item> result = DataContext.Items.Where(x => (x.ItemName.Contains(searchKeyword) ||
x.ItemDescription.Contains(searchKeyword))
.GroupBy(y => y.VersionId)
.Select(z => z.OrderByDescending(item => item.LastModifiedDateTime).FirstOrDefault());
Edit: I don't really care about the order of the result set, i really just care about what item within the grouping is returned. I want to make sure that the last edited Item within a versionId group is return.
Your z parameter contains the individual group objects.
By calling OrderBy inside of Select, you're ordering the items in each group, but not the groups themselves.
You need to also call OrderBy after Select, like this:
.Select(z.OrderByDescending(item => item.LastModifiedDateTime).FirstOrDefault())
.Where(item => item != null)
.OrderByDescending(item => item.LastModifiedTime)

Categories

Resources