Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I convert anonymous type to strong type in LINQ?
    primarykey
    data
    text
    <p>I have an array of ListViewItems ( <code>ListViewItem[]</code> ), where I store a <code>SalesOrderMaster</code> object in each ListViewItem.Tag for later reference.</p> <p>I have some code that right now, goes through each <code>ListViewItem</code> safely casts the .Tag property into a SalesOrderMaster object, then adds that object to a collection of SalesOrders, only after checking to make sure the order doesn't already exist in that collection.</p> <p>The process to <strong>compare</strong> sales orders is expensive, and I would like to convert this to a LINQ expression for clarity and performance. ( I also have the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=348F73FD-593D-4B3C-B055-694C50D2B0F3&amp;displaylang=en" rel="noreferrer">Parallel Extensions to .NET Framework 3.5</a> installed so I can use that to further improve LINQ performance)</p> <p>So without further ado: This is what I have, and then what I want. ( what I want won't compile, so I know I am doing something wrong, but I hope it illustrates the point )</p> <p>What I have: ( Slow )</p> <pre><code>foreach (ListViewItem item in e.Argument as ListViewItem[]) { SalesOrderMaster order = item.Tag as SalesOrderMaster; if ( order == null ) { return; } if (!All_SalesOrders.Contains(order)) { All_SalesOrders.Add(order); } } </code></pre> <p>What I want: ( Theory )</p> <pre><code> List&lt;SalesOrderMaster&gt; orders = (from item in (e.Argument as ListViewItem[]).AsParallel() select new { ((SalesOrderMaster)item.Tag) }).Distinct(); </code></pre> <p>EDIT: I know the cast is cheap, I said the "Compare", which in this case translates to the .Contains(order) operation</p> <p>EDIT: Everyone's answer was awesome! I wish I could mark more than one answer, but in the end I have to pick one.</p> <p>EDIT : This is what I ended up with: </p> <pre><code>List&lt;SalesOrderMaster&gt; orders = (from item in (e.Argument as ListViewItem[]) select (SalesOrderMaster) item.Tag).GroupBy(item =&gt; item.Number).Select(x =&gt; x.First()).ToList(); </code></pre>
    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.
    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