C # Linq SortedList Filtering in SortedList

I have some code in which I am doing some kind of weirdness to get information from a SortedList and back to another SortedList. I make my where clause, then I must individually put all KeyValuePairs back into the new SortedList.

This may not be the most effective or really recommended way to do this, but I cannot find a better way.

Here is the code:

SortedList<DateTime, CalendarDay> most_days = new SortedList<DateTime, CalendarDay>(); List<KeyValuePair<DateTime, CalendarDay>> days = this.all_days.Where ( n => n.Value.IsRequested || n.Value.IsApproved ).ToList(); foreach (KeyValuePair<DateTime, CalendarDay> kvp in days) most_days.Add(kvp.Key, kvp.Value); 

Any ideas on how I can clear this (less, as they say)?

Thanks,

Jonathan

+4
source share
2 answers

Well, you can probably remove the ToList call, which doesn't help you at all.

You can make the calling code easier:

 var dictionary = allDays.Where(n => n.Value.IsRequested || n.Value.IsApproved) .ToDictionary(x => x.Key, x => x.Value); var mostDays = new SortedList<DateTime, CalendarDay>(dictionary); 

... but this will lead to the creation of an intermediate Dictionary<,> , so it is hardly effective.

Another option is that you can write your own ToSortedList extension ToSortedList , for example.

 public static SortedList<TKey, TValue> ToSortedList<TSource, TKey, TValue> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> valueSelector) { // TODO: Argument validation var ret = new SortedList<TKey, TValue>(); foreach (var element in source) { ret.Add(keySelector(element), valueSelector(element)); } return ret; } 

Then the calling code will be simple:

 var mostDays = allDays.Where(n => n.Value.IsRequested || n.Value.IsApproved) .ToSortedList(x => x.Key, x => x.Value); 

I suspect this should be effective enough, as it will always add values ​​to the end of the list at build time.

(For full operation, you want to add overloads that accept custom key mappings, etc., see ToDictionary .)

+9
source

Not a direct answer to your question (sorry!) - more a question to a question:

  • Do you really need SortedList output?
  • Or can you survive with IEnumerable , where the results are in the correct order?

If you never intend to add / insert more elements to the mostDays collection after you created it, then you could just create an IEnumerable with var mostDays = allDays.Where(n => n.Value.IsRequested || n.Value.IsApproved);

+2
source

Source: https://habr.com/ru/post/1345051/


All Articles