Querying Nested Dictionaries using LINQ
I'm developing a POS system and I need to check whether the database tables on each terminal are out of sync.
I maintain a Dictionary of terminal information, each of which has Dictionary containing table ids with a CRC for each table. Below is simplified description of what I've got so far (i'm using VB.NET but I've stripped out a lot of stuff to hopefully clarify things):
e.g. TerminalList = Dictionary(Of Integer, TerminalInfo)
class TerminalInfo
TerminalID: Integer
TableCRCs: Dictionary(Of String, TableInfo)
class TableInfo
TableID: String
CRC: UInt32
TerminalID: 1
TableID: A CRC: aa10
TableID: B CRC: 1234
TerminalID: 2
TableID: A CRC: aa10
TableID: B CRC: 1234
TerminalID: 3
TableID: A CRC: 12be
TableID: B 开发者_如何学PythonCRC: 1234
Is it possible for me to create a LINQ query that will build a list of distinct TableIDs and CRC's?
i.e. A aa10
A 12be
B 1234
If the count of this query is greater than the number of tables that i'm interested in then I know that a terminal is out of sync. I'm not interested in which terminal or which table is out of sync, only that there is a difference.
TIA,
Simon
Sure. You didn't specify a language so I hope that C# is okay (I'm not fluent in VB.NET but I can help you if you need help translating):
var query = TerminalList.SelectMany(kvp => kvp.Value.TableCRCs.Values)
.GroupBy(info => new { info.TableID, info.CRC });
foreach (var result in query) {
Console.WriteLine(
String.Format(
"{0}|{1:x}",
result.Key.TableID,
result.Key.CRC
)
);
}
The key to this is using SelectMany
to flatten the nested enumerations of TerminalInfo
s into one enumeration. From there it's just a usual GroupBy
operation to get the desired result.
精彩评论