I have a C# dictionary with a key of statecode and a list of a classtype. Is there away I can take only those dictionary items that have a FilnameId = 7 , and copy only those items to a second dictionary? I would like to do this without iterating through the dictionary if possible. Any and all direction would be most appreciated. My dictionary and class are below.
-Jason
public class FirstReportsData
{
public FirstReportsData() { }
public int Id { get; set; }
public string Policy { get; set; }
public int FileNameId { get; set; }
public string StateCode { get; set; }
}
Dictionary<string, List<FirstReportsData>> dicFsrFileNameId1 =
new Dictionary<string, List<FirstReportsData>>();
4
Answers
There is no way to filter a dictionary by values properties without iterating through all items…even if you use Linq, there will still be a iteration happening behind the scene
It depends on what do you mean by "iterating". If you don’t want to write
for
/foreach
loops then you can go with LINQ:If you need to rebuild the dictionary then use
GroupBy
:Otherwise no, since your data structure is not a dictionary from
FileNameId
to collection of files, you will need to go through all theFirstReportsData
stored in the dictionary.As previously has been mentioned, may you don’t want to make a traditional for loops but iteration will run under the hood.
you can use:
This code converts directly into a dictionary with the same structure. Technically, it is an iteration, but there is no for loop. It preserves the same structure and takes into account that the StateCode value is always the same for each list in the input dictionary.