Pawli
Pawli

Reputation: 1

List of lists of each row from SQL database using Entity Framework & C#

I have database and I'm using Entity Framework to create models (database first). I want to loop somehow through my model so that I can create a list of each row. Then I want to create list of those lists. Also lists have to be lists of objects not strings.

Model class:

public class person
{
    public int ID {get; set;}
    public string Code {get; set;}
    public int Time {get; set;}
    public string Name {get; set;}
}

Now I have such a person in the database and I want to create a list that contains ID, Code, Time and Name taken from one row. And then I want to create a list of those Person lists. I assume that I should use foreach or for loop but I don't know how should I start.

Edit: I have database that looks like this:

ID | Code | Time | Name
 1    200    10    Paul
 2    201    20    Tom
 3    203    25    Jacob
 4    208    10    Agnes

Now i want to create a list with one row. That list should look like:

List<1,200,10,Paul>

Then i want to create or rather add to list of lists each list created from those rows. So that i would have list that contains lists of Persons.

Upvotes: 0

Views: 1366

Answers (3)

Steve Greene
Steve Greene

Reputation: 12304

Here is one way to create a <List<List<Person>>:

[HttpGet]
public ActionResult PersonIndex()
{
    List<List<Person>> personLists = new List<List<Person>>();
    var personsCodeA = context.Persons.Where(p => p.Code == "A").ToList();
    var personsCodeB = context.Persons.Where(p => p.Code == "B").ToList();
    var personsCodeX = context.Persons.Where(p => p.Code == "X").ToList();
    personLists.Add(personsCodeA);
    personLists.Add(personsCodeB);
    personLists.Add(personsCodeX);
    return View(personLists);
}

Now in the view (or where ever) you could do:

foreach (var currentList in personLists)
{
    // process each list
    console.writeline(string.Format("People in code {0}:",currentList[0].Code));  //todo null check
    foreach (var person in currentList])
    {
        // process each person in the current list
        console.writeline(string.Format("  Person: {0}",person.Name));  //todo null check
        var personID = person.ID;
        var personCode = person.Code;
        var personName = person.Name;
        var personTime = person.Time;
    }
}

Upvotes: 0

V Zabavnov
V Zabavnov

Reputation: 60

If you want to just go through list of Person's data item you need just foreach:

foreach(var data in ctx.Persons.Select( p => new {p.ID, p.Code, p.Time, p. Name})){
    // here you have data object with 4 items
}

Upvotes: 0

NetMage
NetMage

Reputation: 26917

I can think of no legitimate reason to do this, but perhaps this is what you mean?

var listOfLists = db.Persons.Select(p => new List<object> {
    (object)p.ID,
    (object)p.Code,
    (object)p.Time,
    (object)p.Name
}).ToList();

Upvotes: 1

Related Questions