简体   繁体   中英

Using Linq to do: Compile a list of all lists within a list of objects

I'm sure that Title is clear as mud so let me throw out an example and see if someone can point me in the right direction:

public class topObj
{
    public List<midObj> Mids { get; set; }
    public List<botObj> Bots { get { // do some LINQ magic here } }
}
public class midObj
{
    public List<botObj> Bots { get; set; }
}
public class botObj
{
}

So, from the top object I'm trying to get a list of all bottom objects that are in a List<> of any of the middle objects that are in the List<> from the top object.

Right now I have something like this:

public List<botObj> Bots
    {
        get
        {
            List<botObj> lst = new List<botObj>();
            foreach (midObj mo in Mids)
            {
                lst.AddRange(mo.Bots);
            }

            return lst;
        }
    }

It works, of course, but I have to assume there's a way for LINQ to do this in fewer lines.

 get { return Mids.SelectMany(mid => mid.Bots).ToList(); }

I'd also at least consider just returning IEnumerable<botObj> rather than a List , so that you only spend the effort evaluating it all and putting it in a list if you really need to. If you know what you're doing by using a list though, feel free to ignore this comment.

you will have to do something like this:

get{ Mids.SelectMany(x => x.Bots).ToList(); }

Hope it helps!

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