Jamie Keeling
Jamie Keeling

Reputation: 9966

Returning a property of type List<>

I'm currently trying to return a match to a Foreach statement which is contained in a list. I have a class that has a List of string, i'm using this as a collection of tracks.

I'm trying to perform a check to see if the given track i pass in through is a match to any tracks stored in the object (CD.cs) and if so return the entire CD's details.

I'm unsure as to how to so it, unfortunatly i've not used lists as much as i should do.

Here's a snippet of the Track Property: (Virtual as i'm overriding it in another class)

public virtual List<string> Track
    {
        get
        {
            return _track;
        }
        set
        {
            value = _track;
        }
    }

Here is the method i'm trying to use to return a match, quite easy to see where i'm going wrong i imagine. :

public CD FindTrackInCD(string track)
{
        foreach (CD testCD in _cdCollection)
        {
            **//If given track matches any tracks in the list
            if (testCD.Track == track)
            {
                //Return the matching CD
                return trackInCD;
            }**
        }

        throw new ArgumentException("No matches found");
 }

The method i have in bold is the problem area, my compiler shows me this warning:

Operator '==' cannot be applied to operands of type 'System.Collections.Generic.List<string>' and 'string'

Can anyone shed some light on how to fix this?

Thanks!

Upvotes: 0

Views: 295

Answers (2)

HakonB
HakonB

Reputation: 7075

You should do something like:

foreach (CD testCD in _cdCollection)
    {
        if (testCD.Track.Contains(track))
        {
            //Return the matching CD
            return testCD;
        }
    }

Upvotes: 2

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68687

Rename it to Tracks and then you would use it testCD.Tracks.Contains(track). Right now you are, as your error says, comparing a string and a list.

Upvotes: 1

Related Questions