Search code examples
listgenerics.net-2.0

Comparing two generic lists by ID in .NET 2.0


I am posting because I cannot find good ASP.NET 2.0 examples for this.

I have two lists I want to compare:

List 1:

List<Article> articleResult = new List<Article>();

Article has ID

List 2:

List<TaggedContent> tagResult = new List<TaggedContent>();

TaggedContent has ContentID

I want to find all tags that have a matching Article ID and return the string TaggedContent.TagName

The return value is a List<string> of TagName.

I am using ASP.NET 2.0 (sorry!).

Can somebody help out? Thanks you.


Solution

  • Well, obviously it would be a bit easier with LINQ, but hey... I would probably write:

    Dictionary<int, string> tags = new Dictionary<int, string>();
    foreach (TaggedContent content in tagResult)
    {
        tags[content.ContentID] = content.TagName;
    }
    
    List<string> matchingTagNames = new List<string>();
    foreach (Article article in articleResult)
    {
        string name;
        if (tags.TryGetValue(article.ID, out name))
        {
            matchingTagNames.Add(name);
        }
    }
    

    In other words, use a dictionary as an intermediate lookup from ID to name. Let me know if any of this is confusing.