简体   繁体   中英

LINQ to Objects: How to join different properties in the same List of objects

Consider I am having an Item object that has below structure

Name         Parent Item Name
Service 1   
Stock 1      Service 1
Stock 2 

[UPDATED]:

So if an item has a Parent Item Name it becomes a sub item. I want to verify that all parent item names are valid Names value. For example as in the sample data Stock 1 is considered as a sub item as it has Service 1 as a Parent Item to it and Service 1 is a valid Item Name because it is already there in Name I have tried doing the below but this does not return the result:

var aa = from item in items
                 join
                     item2 in items
                     on item.Name equals item2.ParentRef.Value.ToString()
                 select new { item.Name };

To make it more readable here are 2 queries:

var listOfNames = items.Select(t => t.Name);

var answers = items.Where(item => i.ParentItemName != null && 
                         !listOfItems.Contains(i.ParentItemName));

The answers give you a list of non valid items.

This should return the list of items as expected by Join

items.Select(x=>items
             .select(y=> {
                           if(x.Name == y.ParentName)
                             return y;
                           else
                             return null;
                          })
             ).Where(x=>x!=null)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM