0

Supposing I have this query:

var ps = from p in dc.Products
         let text =
             (from t in p.Text
              orderby t.Language == "ja" descending
              select t).FirstOrDefault()
         select new { p.Id, text.Name };

Is there any way to refractor the query being assigned to text?

My guess is that I need to make it an Expression<Func<Product, string, ProductText>>, but I don't know how I'd invoke it.

By the way, if there are more efficient ways to do this, I'd be happy to know.

Thanks,

Rei

Edit: To clarify, the idea is that if Japanese isn't available, I want it to fall back on whatever other language is available.

Maybe this is more efficient?

let text = p.Text.FirstOrDefault(t => t.Language == "ja") ?? p.Text.FirstOrDefault()

Either way, my main question is about how I might make text query reusable -- because it's rather unintuitive, and I can picture myself or someone else doing it wrong in the future.

1 Answer 1

1

EDITED BASED ON COMMENT

var ps = dc.Products.Select(p => new 
{
    Id = p.Id, 
    Text = p.Text.OrderBy(t=> t.Language == "ja").First()
})
.Select (x => new
{
    Id = x.Id,
    Name = x.Name,
    ...
});
Sign up to request clarification or add additional context in comments.

3 Comments

Not quite, because I want it to fall back on whatever language is available. Also, it's likely that I'll be wanting more than just Name -- hence the let.
Makes sense, although I suspect you'd really want to fall back to a specific language rather than some random one?? How about the edited version then? Although now it's pretty much identical to what you started with.
Hmm yeah, that looks quite close to my first one. I'm guessing the executed query is pretty much the same. Falling back to a particular language would be good (probably English), but I'll probably worry about that later if I ever end up with a third language. Should be able to just add a then by fallbackPriority or something along those lines. Right now I'm only worried about Japanese and English.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.