mat1c
mat1c

Reputation: 95

Need "Method return type" of data selected with LINQ from DataTable

I have a method, which takes data received from database, and it takes only data which has a specific day:

private static **return type** FilterDataByDay(DataTable dt, string nameOfTheDay)
    {
         var data = dt.AsEnumerable().Select(x => new
            {
                code = x.Field<string>("Code"),
                day= x.Field<string>("Day"),
                name= x.Field<string>("Name"),
                startTime= x.Field<int>("StartTime"),
                endTime= x.Field<int>("EndTime")

            })
                                    .Where(x => x.day.Equals(nameOfTheDay))
                                    .ToList();

        return data ;
    }

The problem is I don't know how to return data from this method, that other method could take it ant print it out, every element like of each row, it should let me print something like:

    foreach(var variable in "the retuned data from method")
    {
     Console.WriteLine(variable.code +" "+ variable.day + ..etc...
    }

Upvotes: 1

Views: 197

Answers (3)

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

The thing about anonymous types is that they're not named, e.g. anonymous.

The best course of action is to define your own class with the appropriate properties after which you can return IEnumerable<SomeClass>.

Upvotes: 2

Ondrej Janacek
Ondrej Janacek

Reputation: 12616

Defining a proper class that would encapsulate the loaded data is probably the best way to go. But if you are dealing with data you will not need later and you don't pass them to much around, you can leverage the Tuple class. It will look slightly awkward, but if it is just your code and it is not a part of a public API then it is also usable.

Your return type would then be IEnumerable<Tuple<string, string, string, int, int>>

Upvotes: 2

Royi Namir
Royi Namir

Reputation: 148524

You could create a Wrapper class and then you'll have IEnumerable<MyClass>

or you can use IEnumerable<dynamic> , but this way - you wont have intellisence.

Upvotes: 2

Related Questions