开发者

How do I substitute one value for a property in a LINQ query result for another value?

I have the following T-SQL that replaces blank values with '[Unknown]'. How can I achieve this in a LINQ to EF query?

select distin开发者_如何学Goct case when CostCentre = '' then '[Unknown]' else CostCentre end as CostCentre


with a projection:

var result = ctx.Source.Where(...).Select(i => CostCentre == "" ? "Unknown" : CostCentre);

should give you a IQuerialable of strings.


I suspect that the best solution for you is in using an anonymous type in your select—i.e. you're creating a custom/calculated property in a one-off class situation. Selecting an anonymous type allows you to do this:

var items = from testItem in context.TestItems
            select new { CostCentre = (testItem.CostCentre == "" ? "[Unknown]" : testItem.CostCentre) };

This will result in items being a custom IQueryable type where each item has a single property of CostCentre that is type string. If all you really want is the strings, you can end up with an IQueryable<string> if you simplify it thus:

var items = from testItem in context.TestItems
            select testItem.CostCentre == "" ? "[Unknown]" : testItem.CostCentre;

I hope this helps. You'll have bigger complications if you want more than the one property, but this is a good starting point.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜