The first? One? Or by default?

I searched StackOverflow, but still can't figure out the correct syntax for using Single, First (or default) queries.

I am ready to make a request to first intercept the translation in a particular language. If there is no such translation on db, get the first one in English.

Here is what I got so far:

locale = "ja-jp";

var items = from c in db.Contents.Include("Translation")
            where c.RegionalInfo.Any(x => x.RegionId == locale)
            select c;

Edit Notation: items is IEnumerable

+5
source share
5 answers

From your explanation, it looks like you want to get the value if it is found, and if it is not used for translation into English. Consider the following:

locale = "ja-jp"; 

var itens = from c in db.Contents.Include("Translation") 
            where c.RegionalInfo.Any(x => x.RegionId == locale) ||
                  c.RegionalInfo.Any(x => x.RegionId == "en")
            order by (c.RegionalInfo.RegionId == "en", "zzzz", c.RegionalInfo.RegionId) 
            select c; 
var foundItem = items.FirstOrDefault();
if (foundItem != null)
{ ... }

reocrds, , . , ( ). . , orderby, , , .

+1

- .

var item = (from c in db.Contents.Include("Translation")
        where c.RegionalInfo.Any(x => x.RegionId == locale)
        select c).FirstOrDefault();
if (item != null)
   ...
+4

Select, Where .. , . First, Last, Single (+ XXXOrDefault) , .

, IEnumerable<T> IQueryable<t>, :

var item = (from c in dbo.Contents.Include("Translation")
            where c.RegionInfo.Any(x => x.RegionId == locale)
            select c).FirstOrDefault();

... ..

+3
source

Or, if you prefer the syntax of the non-Linq method , you can do something like this:

var item = dbo.Contents.Include("Translation").FirstOrDefault(m => m.RegionInfo.Any(n => n.RegionId == locale));
+1
source

Use the extension DefaultIfEmptyto set the default value for an empty sequence.

0
source

All Articles