Search code examples
c#listcontains

Why is the return is List<char>?


I am trying to pull file names that match the substring using "contains" method. However, return seem to be List<char> but I expect List<string>.

private void readAllAttribues()
{
    using (var reader = new StreamReader(attribute_file))
    {
        //List<string> AllLines = new List<string>();
        List<FileNameAttributeList> AllAttributes = new List<FileNameAttributeList>();

        while (!reader.EndOfStream)
        {
            FileNameAttributeList Attributes = new FileNameAttributeList();
            Attributes ImageAttributes = new Attributes();
            Point XY = new Point();
            string lineItem = reader.ReadLine();
            //AllLines.Add(lineItem);
            var values = lineItem.Split(',');

            Attributes.ImageFileName = values[1];
            XY.X = Convert.ToInt16(values[3]);
            XY.Y = Convert.ToInt16(values[4]);
            ImageAttributes.Location = XY;
            ImageAttributes.Radius = Convert.ToInt16(values[5]);
            ImageAttributes.Area = Convert.ToInt16(values[6]);
            AllAttributes.Add(Attributes);
        }
        List<string> unique_raw_filenames = AllAttributes.Where(x => x.ImageFileName.Contains(@"non")).FirstOrDefault().ImageFileName.ToList();
        List<string>var unique_reference_filenames = AllAttributes.Where(x => x.ImageFileName.Contains(@"ref")).FirstOrDefault().ImageFileName.ToList();


        foreach (var unique_raw_filename in unique_raw_filenames)
        {
            var raw_attributes = AllAttributes.Where(x => x.ImageFileName == unique_raw_filename).ToList();

        }
    }
}

Datatype class

public class FileNameAttributeList
        {   // Do not change the order
            public string ImageFileName { get; set; }
            public List<Attributes> Attributes { get; set; }

            public FileNameAttributeList()
            {
                Attributes = new List<Attributes>();
            }
        }

Why is FirstOrDefault() does not work ? (It returns List<char> but I am expecting List<string> and fails.


Solution

  • In your code

    List<string> unique_raw_filenames = AllAttributes.Where(x => x.ImageFileName.Contains(@"non")).FirstOrDefault().ImageFileName.ToList();
    

    FirstOrDefault() returns the first, or default, FileNameAttributeList from the list AllAttributes where the ImageFileName contains the text non. Calling ToList() on the ImageFileName then converts the string value into a list of chars because string is a collection of char.

    I think that what you are intending can be achieved by switching out FirstOrDefault to Select. Select allows you to map one value onto another.

    So your code could look like this instead.

    List<string> unique_raw_filenames = AllAttributes.Where(x => x.ImageFileName.Contains(@"non")).Select(x => x.ImageFileName).ToList();
    

    This then gives you a list of string.