Hi I have a list of files. I need to make a dictionary kind of data structure in the format <file, DateTime>, and then sort it based on DateTime and remove latest 'n' entries. I did this,
filesDictionary = files.ToDictionary(x => x, x => x.CreationTime);
But since Dictionaries are unordered, I thought it is safe to use list of key,value pair in C#,But not sure how to actually write the code similar to above.
I considered sortedLists.But they sort based on Key, I want to sort based on value.
(Also please advise if there are any better efficient option to do this.)
CodePudding user response:
It would be significantly easier to invert your order of operations.
Order the files by their creation date descending so that the newest files are on top. You can skip the first n files you don't want, then make it into a dictionary.
var fileDictionary = files.OrderByDescending(x => x.CreationDate)
.Skip(n)
.ToDictionary(x => x, x => x.CreationTime)
CodePudding user response:
You don't need a dictionary or something else for it. You can sort your collection and skip the first 10 times and take the rest.
// if you want first 10 items
var latest10Items = files.OrderByDescending(r=> r.CreationTime).Take(10).ToList();
// if you want the items except first 10
var rest = files.OrderByDescending(r=> r.CreationTime).Skip(10).ToArray();
// if you want the items except first 10 in a dictionary format
var rest = files.OrderByDescending(r=> r.CreationTime).Skip(10).ToDictionary(r=> r.CreationTime);
CodePudding user response:
You can have a
public class KeyValue<TKey, TValue>
{
public TKey Key { get; set; }
public TValue Value{ get; set; }
}
with
filesDictionary = files
.Select(x=> new KeyValuePair<string, DateTime>()
{
Key = x,
Value = x.CreationTime
})
.OrderByDescending(x => x.Value)
.Skip(n);