Question

I have a list collection in my class library that uses a sql datareader to returns a list of family details

public class Dataops
   {
      public List<Details> getFamilyMembers(int id)
       {
          some of the database code..

          List<Details> fammemdetails = new List<Details>();
          Details fammember;

          while (reader.Read())    
           {   
            fammemdetails = new Details((
            reader.GetString(reader.GetOrdinal("PHOTO")));

            fammemdetails.add(fammember);
            }   
              return fammemdetails;
          }
        }

So i reference the dll to my project and would like to bind an image to one of my datareader values.

MyProject

DataOps ops = new DataOps();

myimage.ImageUrl = ??? (how do i access the list collections return image value here?

I am able to bind a datasource to the entire method like so

dropdownlistFamily.DataSource = mdb.GetFamilyMembers(id);

But cant figure out how to just grab a single value from there

Was it helpful?

Solution

You can use First/FirstOrDefault, Single/SingleOrDefault depending on your requirement. This would give you a single item from the List and you can access its ImageUrl property.

var item = mdb.GetFamilyMembers(id).FirstOrDefault();
if(item != null)
    myimage.ImageUrl = item.ImageUrlProperty;

If you want to get some specific object from the list based on the condition then you can do:

var item = mdb.GetFamilyMembers(id).FirstOrDefault(r=> r.ID == someID);

You may see: LINQ Single vs SingleOrDefault vs First vs FirstOrDefault

OTHER TIPS

You can use FirstOrDefault or SingleOrDefault. Or specify a predicate and use Where.

var firstValue = ops.getFamilyMembers(1).FirstOrDefault();

Use index to access particular record in the collection. You will need to ensure that element exists at the index you given in indexer, otherwise you will get exception. It is zero based index so first element will be at zero index.

var familyMembers =  mdb.GetFamilyMembers(id);
if(familyMembers.Count > 0)
    myimage.ImageUrl = familyMembers[0].ImageURLProperty;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top