Note that there are some explanatory texts on larger screens.

plurals
  1. POC# listbox Collection syntax
    primarykey
    data
    text
    <p>While learning C# pretty fast, I am stumbling on this Collection syntax problem.</p> <p>I added a number of objects of my own type MyItem to listbox lstData. Now I need to search in this listbox and thought of using the elegant LINQ notation like:</p> <pre><code>lstData.Items.Where(x =&gt; x.Text == SearchString) </code></pre> <p>but the Items of a listbox does not have a .Where(), although I did include the "using System.Linq;" namespace.</p> <p>So I tried:</p> <pre><code>foreach (MyItem item in (MyItem)lstData.Items) </code></pre> <p>but this gives the build error: Cannot convert type 'System.Windows.Forms.ListBox.ObjectCollection' to 'MySandbox.frmListboxDemo.MyItem'.</p> <p>I did manage to write something workable:</p> <pre><code> for (int i = 0; i &lt; lstData.Items.Count; i++) { MyItem item = (MyItem)lstData.Items[i]; if (item.Text == SearchString) { lstData.SetSelected(i, true); break; } } </code></pre> <p>and a similar version like:</p> <pre><code> var item_enum = lstData.Items.GetEnumerator(); while (item_enum.MoveNext()) { etc etc... } </code></pre> <p>which turned out to be 2 lines longer, and without figuring what could replace 'var'.</p> <p>I am not really sure I understand how to use Collections, ObjectCollections, Enumerators etc, but am eager to learn. Especially if a .Where() version is possible and/or better.</p> <hr> <p>Thanks for all your answers. I ended up with this solution:</p> <pre><code> var item_iter = lstData.Items.Cast&lt;MyItem&gt;() .Where(x =&gt; x.Text.Trim().ToLower() == txtItemName.Text); foreach (MyItem item in item_iter) { int i = lstData.Items.IndexOf(item); lstData.SetSelected(i, true); break; } </code></pre> <p>I don't know if this is really much better than the "fortran" way (see above), but it does teach me methods I can use in other C# queries.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload