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.
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.
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().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With