Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use linq to sql to select one column from row

I am using this C# with linq to sql:

string currentLabel = from s2f in stream2FieldTypesTable
                      where s2f.s2fID == item.s2fID
                      && (s2f.s2fLabel != item.s2fLabel || s2f.s2fIsRequired != item.s2fIsRequired)
                      select s2f.s2fLabel;

I am getting a compiler error saying i can't assign type System.Linq.IQueryable<string> to string.

I tried this code:

string currentLabel = from s2f in stream2FieldTypesTable
                      where s2f.s2fID == item.s2fID
                      && (s2f.s2fLabel != item.s2fLabel || s2f.s2fIsRequired != item.s2fIsRequired)
                      select s2f.s2fLabel.ToString();

And that returns the same error. I'm sure this is a simple thing. what am I missing? I just want the first s2fLabel that matches the where clause.

like image 533
quakkels Avatar asked Dec 18 '10 19:12

quakkels


People also ask

How do I Select specific columns in Entity Framework?

We can do that simply by using the “new” operator and selecting the properties from the object that we need. In this case, we only want to retrieve the Id and Title columns. There.

How do I return a single value from a list using LINQ?

var fruit = ListOfFruits. FirstOrDefault(x => x.Name == "Apple"); if (fruit != null) { return fruit.ID; } return 0; This is not the only road to Rome, you can also use Single(), SingleOrDefault() or First().


1 Answers

Actual type of your query will be IEnumerable. LINQ has a concept of deffered execution, in order to get you query actually exectuted you need to call a method that will iterate over IEnumerable:

    string currentLabel = (from s2f in stream2FieldTypesTable
                          where s2f.s2fID == item.s2fID
                          && (s2f.s2fLabel != item.s2fLabel || s2f.s2fIsRequired != item.s2fIsRequired)
                          select s2f.s2fLabel)
                         .FirstOrDefault();

For getting exact one instanse it can be FirstOrDefault() method or SignleOrDefault() or just First() or Single(). The only difference is that methods without "OrDefault()" will throw an exception if enumeration will not satisfy their expectations, and methods with "OrDefault()" will just return null.

Edit

The dirrerence between Single and First is that Single expects exact one element in the collection and First expects at least one element.

like image 146
Restuta Avatar answered Nov 15 '22 00:11

Restuta