How can I convert anonymous type to strong type in LINQ?

后端 未结 3 1502
南方客
南方客 2021-02-07 05:54

I have an array of ListViewItems ( ListViewItem[] ), where I store a SalesOrderMaster object in each ListViewItem.Tag for later reference.

I ha

3条回答
  •  暖寄归人
    2021-02-07 06:20

    I see nobody has addressed your need to convert an anonymous type to a named type explicitly, so here goes... By using "select new { }" you are creating an anonymous type, but you don't need to. You can write your query like this:

    List orders = 
        (from item in (e.Argument as ListViewItem[]).AsParallel() 
        select (SalesOrderMaster)item.Tag)
        .Distinct()
        .ToList();
    

    Notice that the query selects (SalesOrderMaster)item.Tag without new { }, so it doesn't create an anonymous type. Also note I added ToList() since you want a List.

    This solves your anonymous type problem. However, I agree with Mark and Guffa that using a parallel query here isn't you best option. To use HashSet as Guffa suggested, you can do this:

    IEnumerable query = 
        from item in (ListViewItem[])e.Argument
        select (SalesOrderMaster)item.Tag;
    
    HashSet orders = new HashSet(query);
    

    (I avoided using var so the returned types are clear in the examples.)

提交回复
热议问题