Search code examples
c#genericscheckedlistbox

Filtering list objects from another list


I have the following class in my C# .NET 3.5 win forms app:

class Field {

string objectName;
string objectType;
string fieldName;
string fieldValue;


}

and a List fieldList that is a datasource for a checkedlistbox. This listbox shows all the distinct objectNames from my fieldList collection.

I want to create another checkedlistbox that contains fieldNames, but only shows fieldnames that have an associated checked objectName in the first list box.

So my question is how can I query the DataSource of the original list of objectNames to return the distinct set of fieldNames that are associated with a selected objectName?

That is not very easy to read so I will give an example:

Field1 {

objectName = 'objA'
FieldName = 'FieldA'

}

Field2 {

objectName = 'objA'
FieldName = 'FieldB'

}


Field3 {

objectName = 'objB'
FieldName = 'FieldA'

}

Field4 {

objectName = 'objC'
FieldName = 'FieldC'

}

So suppose in my checkbox I select objectNames objA and objB. Then my returned fields would be 'FieldA' and 'FieldB'.

How can I achieve this using LINQ or filtering my generic list of Fields? Can I utilise the 'select' or 'where' methods that are available to a list?


Solution

  • var selectedNames = ... // List of selected names
    var selectedFields = (from f in fieldList
                          where selectedNames.Contains(f.objectName)
                          select f.FieldName).Distinct().ToList();