简体   繁体   中英

How to create a List of lists from a specified number of models/classes?

Well, the titled of this question/doubt I think it is pretty self-explanatory, but here go the idea (Using simple terms): I have Files (In a project) that contain a class (each one of 'em) which has objects and methods (From Models), and one of these methods returns a List. I wanna create another class to generate a new List that will contain all those lists mentioned above. If this is possible mainly in C#, I would appreciate your points of views in how to create this. Thanks in advance for tips, helps and good intentions!!!

I hope you can understand me, because I'm very bad in describing problems. :D

What you're looking for is SelectMany:

#region Terrible Object

var hasAllTheItems =
        new[]
        {
                new[]
                {
                        new
                        {
                                Name = "Test"
                        }
                },
                new[]
                {
                        new
                        {
                                Name = "Test2"
                        },
                        new
                        {
                                Name = "Test3"
                        }
                }
        };

#endregion Terrible Object

var a = hasAllTheItems.Select(x => x.Select(y => y.Name));
var b = hasAllTheItems.SelectMany(x => x.Select(y => y.Name));
var c = hasAllTheItems.Select(x => x.SelectMany(y => y.Name));
var d = hasAllTheItems.SelectMany(x => x.SelectMany(y => y.Name));

Assert.AreEqual(2, a.Count());
Assert.AreEqual(3, b.Count());
Assert.AreEqual(2, c.Count());
Assert.AreEqual(14, d.Count());

A: {{Test}, {Test2, Test3}}

B: {Test, Test2, Test3}

C: {{T, e, s, t}, {T, e, s, t, 2, T, e, s, t, 3}}

D: {T, e, s, t, T, e, s, t, 2, T, e, s, t, 3}

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