Home > Software engineering >  Given list of classes, how to make list\array from specific property of class?
Given list of classes, how to make list\array from specific property of class?

Time:06-23

I have a class:

public class MyField
{
    private string fieldName;
    public string FieldName
    {
        get { return fieldName; }
        set { fieldName = value; }
    }

    private string fieldValue;
    public string FieldValue
    {
        get { return fieldValue; }
        set { fieldValue = value; }
    }

    private string fieldValidation;
    public string FieldValidation
    {
        get { return fieldValidation; }
        set { fieldValidation = value; }
    }

    private bool fieldValid;
    public bool FieldValid
    {
        get { return fieldValid; }
        set { fieldValid = value; }
    }
}

and then I have a list made of them:

private IList<MyField> myFields;

myFields = new List<SpectraNameField>()
{
    new SpectraNameField{FieldName = "FirstField", FieldValue="", FieldValid = false, FieldValidation="" },
    new SpectraNameField{FieldName = "SecondField", FieldValue="", FieldValid = false, FieldValidation="" }
};

I then populate FieldValue for each member of the list through my XAML, but let's say as an example I just say:

myFields[0].FieldValue = "Value0";
myFields[1].FieldValue = "Value1";

At the end I need to get all the values of FieldValue for each MyField joined using "_" (i.e. I need to get string "Value0_Value1") How do I get list or array of all the FieldValue of my list of MyField?

CodePudding user response:

Use .Selectto get the values

 var fieldValues = myFields.Select(f => f.FieldValue);

Use string.Join to combine multiple strings

var joinedString = string.join("_", fieldValues);
  • Related