I have a field object and I create a list of fields:
class Field {
string objectName;
string objectType;
string fieldName;
string fieldValue;
//constructor...
}
List<Field> fieldList = new List<Field>();
Suppose I wanted to query this list to return a collection of distinct object names (to then be inserted into a checkedlistbox. How would I go about doing that?
I imagine some LINQ magic can manage this?
-
var q = from Field f select f.objectName; q = q.Distinct();
chkListbox.DataSource = q;
-
I want to query the list fieldList, not just the class field.
-
Sorry, I mistyped:
var q = from Field f in fileldList select f.objectName;
chkBoxList.DataSource = q.Distinct();
Nathan W : can you fix up your first answer not make a new one. -
The expression should return a List of distinct object names from the list as defined. I converted it to a list since the docs for the CheckedListBox DataSource property indicated that it needs to implement IList or IListSource, not merely IEnumerable.
((ListControl)cbListBox).DataSource = fieldList.Select( f => f.objectName ) .Distinct() .ToList() );
If accessing the checkedListBox as a ListControl doesn't give access to the DataSource (sometimes the docs lie), you could try:
cbListBox.Items.AddRange( fieldList.Select( f => f.objectName ) .Distinct() .ToArray() );
-
Either of these work
Using var
1) var fieldNameCollection = from f in fieldList select f.FieldName; 2) Lambda syntax var fieldNameCollection = fieldList.Select(f => f.FieldName);
Alternately, instead of using var, you can also use IEnumerable fieldNameCollection = fieldList.Select(f => f.FieldName);
-
Brilliant.
I'd like to give everyone some points, but i'll have to go with tvanfosson's answer because he was the first to give a complete description.
Thanks all.
tvanfosson : You can upvote all helpful answers...tvanfosson : FYI...you should add information to your question by editing or leaving comments (once able to) instead of adding an answer -- unless you are answering your own question, which sometimes happens. -
bleh, a problem.
My checkedlistbox does not have the datasource property? This is a winforms apps (not WPF if that makes a difference.)
tvanfosson : Docs say it does http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.aspx. You might have to cast it as a ListControl, though, to access it.
0 comments:
Post a Comment