How can I group two different (first typeof years == IEnumerable<string>
and second typeof occurs = IEnumerable<int>
) sequences into 1 sequence by the next key: if number in occurs
are same, then order by years
, else order by occurs
using only LINQ
?
I've got these sequences in the following way:
var years = some_strings.Select(x => x.Split(' ')[1]);
var occurs = years.Select(x => years.Count(e => e == x));
So variable years
contains only strings with years and occurs
contains count of same years in first sequence.
I cannot understand these techniques in LINQ
.
Will I do something like this?
occurs.GroupBy(x => x ???
Where should I use the second sequence? Maybe I can got these sequences in 1 query and then process it?
UPD
I modified my 2 queries in 1 by using anonymous class(?):
some_strings.Select(x => x.Split(' ')[1]).
GroupBy(x => x).
Select(x => new {num = x.Key, count = x.Count() })
So, there are years and occurs both in it.
I'm trying to get next string:
1 1990
1 1991
1 1992
2 1967
2 1968
5 2010
...
Now, having query with needed values, how can I sort it like foregoing clause?
You're pretty close. This should give you a list of strings similar to your latest update:
var occurences
= years.GroupBy(x => x)
.Select(x => new { Year = int.Parse(x.Key), Count = x.Count() })
.OrderBy(x => x.Count)
.ThenBy(x => x.Year)
.Select(x => string.Concat(x.Count, " ", x.Year))
.ToList();
Using the anonymous type you created, you can:
string.Concat
(Note that int.Parse
will throw an exception if any of your strings in years
are not actually numbers)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.