Search code examples
c#linqlistlookup

How to store and lookup data, based on multiple xml attributes?


I am querying an xml file and returning 3 attributes per selection (each entry that meets my criteria will return 3 attributes details). I need to store these values, and then later look up the first attribute, and return the 2 other stored attributes related to it.

var items = from item in doc.Descendants("SUM")
                        select new
                        {                                    
                            id = (string)item.Attribute("id"),
                            category = (string)item.Attribute("cat"),
                            selection = (string)item.Attribute("sel")
                        };

The above code returns 3 attributes per item found. I need to store those 3 entries so they are associated together, then later perform a lookup on the stored entries. So example, I need to be able to look up a stored value of id=1, and return the corresponding category and selection entry.

I was researching the Lookup method of C# but don't understand how to use it. List's seem like they might work, but I don't know how to store multiple pieces of data into an entry in a list (maybe concatenate into a single entry, but then I'm not sure about performing the lookup on it). Any suggestions regarding how to do this with a LIST or LOOKUP (or other unmentioned way) are appreciated.


Solution

  • You can use Where (or other options, such as FirstOrDefault, etc)to filter this further:

    var items = from item in doc.Descendants("SUM")
                        select new
                        {                                    
                            Id = (string)item.Attribute("id"),
                            Category = (string)item.Attribute("cat"),
                            Selection = (string)item.Attribute("sel")
                        };
    
    var filtered = items.Where(i => i.Id == 1);
    
    // Then use these as needed
    foreach(var item in filtered)
    {
        Console.WriteLine("Cat: {0}, Sel: {1}", item.Category, item.Selection);
    }
    

    The ToLookup method actually serves a very different purpose. It builds a data structure which implements ILookup<T,U>, which is a lookup table where you can easily return all of the items that match a specific key. This is useful if you're going to perform many lookups from your data, but not if you just want to "lookup" items matching a single value.