How to order groupBy items - c#

Having this Linq query which returns grouping of 4 DateTime:
IEnumerable<IGrouping<DateTime, QuoteSnapshotModel>> lista = (from q in quoteModeList
where q.QuoteTradeType == "Q"
select q).GroupBy(n => n.ExceriseDate);
How can I order the groups by DateTime and get only the first group?
meaning **List<QuoteSnapshotModel>**
Also, how can I get only the second List<QuoteSnapshotModel> (according to DateTime)

Try this:
for this you have to create a list<QuoteSnapshotModel> within class QuoteSnapshotModel.
int record = 1;
List<QuoteSnapshotModel> result =
quoteModeList
.Where(x => x.QuoteTradeType == "Q")
.GroupBy(x => x.ExceriseDate,
(a, b) => new QuoteSnapshotModel
{
ExceriseDate = a,
ListQuoteSnapshotModel = b.ToList()
})
.OrderByDescending(t => t.ExceriseDate)
.Skip(record - 1).Take(1).ToList();

Update
You can use only the first group
List<QuoteSnapshotModel> list =quoteModeList.Where(x=>x.QuoteTradeType =="Q")
.GroupBy(x => x.ExceriseDate)
.OrderBy(x=>x.Key)
.FirstOrDefault().Select(x=>x.QuoteTradeType).ToList();
You can use only the second group
List<QuoteSnapshotModel> list =quoteModeList.Where(x=>x.QuoteTradeType =="Q")
.GroupBy(x => x.ExceriseDate)
.OrderBy(x=>x.Key)
.Skip(1).First().Select(x=>x.QuoteTradeType).ToList()

How can I order the groups by DateTime
.OrderBy(g => g.Key) or .OrderBy(g => g.First().ExerciseDate)
and get only the first group?
.First() (or .FirstOrDefault() if it's possible there are 0 groups)
how can I get only the second List (according to DateTime)
.Skip(1).Take(1) or .ElementAt(1) or .Skip(1).First()
Putting it all together:
IEnumerable<IGrouping<DateTime, QuoteSnapshotModel>> lista = (
from q in quoteModeList
where q.QuoteTradeType == "Q"
select q
).GroupBy(n => n.ExerciseDate);
IList<QuoteSnapshotModel> firstQuote = lista.OrderBy(x => x.Key).Select(x => x.ToList()).FirstOrDefault();
IList<QuoteSnapshotModel> secondQuote = lista.OrderBy(x => x.Key).Skip(1).Select(x => x.ToList()).FirstOrDefault();

Related

convert dictionary to list model

var entity = await _abcRepository.get(Id);
var X = entity.GroupBy(c => c.number).Where(grp => grp.Count() == 1).Take(10).ToList();
in images you see [0] and inside of it one more [0].
How can I get that model value.
X[0][0] is not working.
X.Value is not working.
I need to convert that dictionary to model.
Use .Select to normalize aggregation as per your wish.
var X = entity.GroupBy(c => c.number).Where(grp => grp.Count() == 1)
.Select(group => new { GroupKey = group.Key, Items = group.ToList() })
.Take(10).ToList();
You could try something like this:
var entity = await _abcRepository.get(Id);
var results = entity.GroupBy(c => c.number)
.Where(grp => grp.Count() == 1)
.Take(10)
.ToDictionary(grp => grp.Key, grp => grp.First());
Essentially, the lambda you pass in Where method certifies that the groups are created contains only one item. That being said, you can use the First on each group to fetch that one element.

Linq query group by weight

AllWordIDsAndWeightings is a Dictionary<int, double> of unique ID's for words that appear in a search query, along with their corresponding weighting.
Given the following query:
returnedObjectIDs = new List<int>(db.WordObjectMaps
.Where(c =>
c.ForObjectTypeID == TopicObjectTypeID
&& AllWordIDsAndWeightings.Select(w=> w.Key).ToList().Contains(c.WordID)
)
.GroupBy(c => c.ForObjectID)
.Select(c => c.Key)
);
I'd like to modify it so that:
The group by statement contains the sum of word frequency * word weighting for each word. Then I can order by this value descending and take the top n records.
Is this possible?
returnedObjectIDs = new List<int>(db.WordObjectMaps
.Where(c =>
c.ForObjectTypeID == TopicObjectTypeID
&& AllWordIDsAndWeightings.ContainsKey(c.WordID)
)
.Select(c => new { Word = c, Weight = AllWordIDsAndWeightings[c.WordID])
.GroupBy(c => x.Word.Value * c.Weight) // replace with your condition
.Select(c => c.Key)
);

Sorting a dictionary via multiple parameters

I have a dictionary IDictionary answersDictionary<Country, List<Answer>>, where Country contains information on country and List<Answer> is a list of Answer objects, which have a property State that can be final, draft, comment.
I need to sort the dictionary in a way, that its sorted by:
Number of draft answers for country
Number of comment answers for country
By Country.Name
And, at the end get only the keys of the dictionary.
I have done the following:
IDictionary<Country, List<Answer>> answersDictionary = Database.Answer
.GroupBy(a => a.Country).ToDictionary(d => d.Key, d => d.ToList());
answersDictionary.OrderByDescending(d => d.Value.Where(a => a.State == AnswerState.Draft).Count())
.ThenByDescending(d => d.Value.Where(a => a.State == AnswerState.Comment).Count())
.ThenBy(d => d.Key.Name);
And at the end List<Country> finalResult=answersDictionary.Keys;
But, the results are not correct, as they are returned sorted only by Draft and in ascending order. Any suggestions, what's the issue?
You have to assign your second query to a variable. Try this:
IDictionary<Country, List<Answer>> answersDictionary = Database.Answer
.GroupBy(a => a.Country).ToDictionary(d => d.Key, d => d.ToList());
var answerDict = answersDictionary.OrderByDescending(d => d.Value.Count(a => a.State == AnswerState.Draft))
.ThenByDescending(d => d.Value.Count(a => a.State == AnswerState.Comment))
.ThenBy(d => d.Key.Name)
.ToDictionary(d => d.Key, d => d.Value);
List<Country> finalResult = answerDict.Keys.ToList();

Compare Matching Element using single query in Iqueryable

I am trying to compare two List of UserGroup from two different Table using a single query ie, by not hitting DB multiple times.
currently I am fetching all assigned UserGroup in one query, and comparing with all allowed Usergroup in other query.
var query = _context.AppSubOperationUserGroupMappings.Where(filterPredicate)
.Select(x => x.UserGroup)
.ToList();
var allowedUserGroups = _context.Users.Where(x => x.Id == userId)
.Select(x => x.UserGroupUserMappings.Select(y => y.UserGroup))
.First()
.ToList();
return query.Any(a => allowedUserGroups.Any(b => b.Id == a.Id));
How can I merge them into single Query?
Remove ToList and First, use Join and SelectMany
var query = _context.AppSubOperationUserGroupMappings.Where(filterPredicate)
.Select(x => x.UserGroup);
var allowedUserGroups = _context.Users.Where(x => x.Id == userId)
.SelectMany(x => x.UserGroupUserMappings, (x, y) => y.UserGroup);
return query
.Join(
allowedUserGroups,
x => x.Id,
x => x.Id,
(x, y) => false) // doesn't matter what to select
.Any();

Query entity and return back a dictionary

I'm trying to query a view (entity) from the database and return back a dictionary. There are duplicates in the view so I tried groupby and I can't figure it out.
var queryresults = db.MyView.Where(x => x.year == myYear)
.GroupBy(g => new { g.myCode, g.myCodeName})
.ToDictionary(d => d.myCode, d => d.myCodeName);
You should group by dictionary key property if you want to avoid duplicate keys error. Then you can select code name of first item in each group as dictionary entry value:
var queryresults =
db.MyView.Where(x => x.year == myYear)
.GroupBy(x => x.myCode)
.ToDictionary(g => g.Key, g => g.First().myCodeName);

Categories