Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

C# - Linq Query Question?

I have a Dictionary<string, string> with roughly 400 entries that is populated by a pretty expensive database call. I need to extract about 50 or so KeyValuePair objects whose keys all start with a particular string: "TX_VALUE_"

Currently, I am looping over all 400 values using a foreach loop and an If - StartsWith test on each key. If I find one, I add it to a second Dictionary to be returned.

Can I use a Linq query for this? Is this the best way to be extracting these keys?

2 Answers

Relevance
  • 1 decade ago
    Favorite Answer

    Mostly agree with Daniel. Although I think the final foreach loop could be replaced with:

    lr = result.ToList();

    Just curious, do you need the other 350 rows from the query for other reasons? If not, then I would be inclined to tackle this at the database level and only return the 50 rows you need to begin with. That would lower the cost of the DB call. Of course, if you do need the rows for other reasons, then you have to do what you are doing, either with a loop or LINQ. (The loop may actually be faster. If performance is an issue, you might want to measure LINQ vs. your existing code.)

  • 1 decade ago

    Yes, you could do that with Linq to Objects like this:

    var result = from kvp in l

    where kvp.Key.StartsWith("TX_VALUE_")

    select kvp;

    foreach (KeyValuePair<string, string> kvp in result) lr.Add(kvp.Key, kvp.Value);

    If this is the only way you are querying this dictionary then this might be overkill, it would just be simpler to iterate the array like you are doing now. Even with Linq you will still need to iterate over the results to put them in the second dictionary.

Still have questions? Get your answers by asking now.