Select with LINQ

0

I need to recover the code of a division which is a string and return it to show later. The code I have is the following but there is something that does not work and I do not know what it is. Any suggestions?

    public string DivisionCode()
    {

        DataTable tblCollections = clsFrmGlobals.mySet.Tables[0];
        DataTable tblDivisions = clsFrmGlobals.mySet.Tables[2];

        var query = from col in tblCollections.AsEnumerable()
                    from div in tblDivisions.AsEnumerable()
                    where col.Field<int>("DivisionID") == div.Field<int>("DivisionID")
                    && col.Field<int>("CollectionID") == CollectionID
                    select div.Field<string>("DivisionCode");
        return query.ToString();
    }
    
asked by Juan Carlos Marmolejo Martínez 07.06.2018 в 21:56
source

2 answers

2

In principle your query seems correct. The problem is what you do with the result.

In query what you will have after your query is probably a IEnumerable<DataRow> , that is, a collection of rows. To that result you apply a ToString , which will be returned the name of the result class (something like IEnumerable... )

If what you want to do is return the first result of the query, what you should do is use First (if you're sure you're going to have results) or FirstOrDefault (for if you do not have results that return the default value).

In short, in your method change:

return query.ToString();

for

return query.FirstOrDefault().ToString();
    
answered by 08.06.2018 в 09:41
0

It was necessary, in addition to Pikoh's suggestion, to change the order of the consultation. Finally I am like this:

public string DivisionCode()
{            
        var query = from div in clsSilex.tblSXDivision.AsEnumerable()
                        from col in clsSilex.tblSXCollection.AsEnumerable()
                        where col.Field<int>("CollectionID") == CollectionID
                        && col.Field<int>("DivisionID") == div.Field<int>("DivisionID")
                        select div.Field<string>("DivisionCode");

        return query.FirstOrDefault().ToString();
}
    
answered by 08.06.2018 в 21:36