views:

187

answers:

3

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?

+1  A: 
var selectedNames = ... // List of selected names
var selectedFields = (from f in fieldList
                      where selectedNames.Contains(f.objectName)
                      select f.FieldName).Distinct().ToList();
aku
+2  A: 

First, read the object names into an array or list; I'll fake that part. Then it should be something like:

    string[] objectNames = { "objA", "objC" };
    var hashSet = new HashSet<string>(objectNames);

    var qry = (from row in data
               where hashSet.Contains(row.objectName)
               select row.fieldName).Distinct().ToList();

(edit)

To get the selected names (the bit I faked) you could try (untested):

    var selectedNames = namesCheckedListBox.CheckedItems.Cast<Field>()
        .Select(field => field.objectName);
    var hashSet = new HashSet<string>(selectedNames);

(note no need to use Distinct() in the above, since HashSet<T> does that anyway)

Marc Gravell
A: 

Thanks guys. I ended up going with aku's solution because I didnt have to cast things around to new objects.

Marc: Thanks for introducing me to a new data structure!

Alex