根据定义的订单获取值

时间:2012-09-19 17:47:22

标签: c# .net

我目前在db表中有数据如下:

Data in table 
Desc       Value                                                                                                 
BNo        12 
CNo        Null 
ANo        15 
DNo        Null 
ENo        15 

如果ANo为空白,我需要显示BNo。如果BNo为空,则在表格上显示CNo。一旦我找到基于DESC的定义优先级顺序的非空值(在这种情况下为A-E),我需要退出我的方法。如何实现,我可以根据优先级硬编码desc名称,但它希望以更优化的方式实现。请给我任何建议。

3 个答案:

答案 0 :(得分:1)

SQL Server

select top 1 *
from MyTable
where Value is not null
order by [Desc]

MySQL的:

select *
from MyTable
where `Value` is not null
order by `Desc`
limit 1

答案 1 :(得分:0)

听起来你有办法订购清单,因为你按“优先顺序”说明。不确定这个优先级是什么,但是对于该示例,我们假设它按字母顺序“Desc”。我们还假设(为简单起见)这些值在字典中。鉴于此,你可以写一个Linq语句......

dict.OrderBy(o => o.Key).FirstOrDefault(d => d != null);

...例如

Dictionary<string,string> dict = new Dictionary<string,string>();
dict.Add("BNo", "12");
dict.Add("CNo", null);
dict.Add("ANo", null);
dict.Add("DNo", null);
dict.Add("ENo", "16");

Debug.WriteLine(dict.OrderBy(o => o.Key).FirstOrDefault(d => d.Value != null));

这将返回第一个非null值。如果所有值都为null,则返回null。

这里可能存在一些不正确的假设,但OrderBy和FirstOrDefault应该能够以实现目标所需的任何方式使用。唯一需要改变的是“o.Key”和“d.Value”来引用你的实际属性。
例如,如果此信息属于此类......

class Info
{
    public string Desc { get; set; }
    public int? Number { get; set; }
}

你有一个列表,如......

List<Info> info = new List<Info>();

然后你可以写......

var returnValue = info.OrderBy(o => o.Desc).FirstOrDefault(d => d.Number.HasValue);

答案 2 :(得分:0)

表中的Desc字段的ANo,BNo,CNo等值,或表中的Desc,ANo,BNo .. etc字段。我怀疑是因为你只是这些实际上是联系方式。 如果是第一个,RedFilter会给你答案。 如果是第二个,则动态查询可以是一个选项。 只需按优先级顺序将字段添加到数组中,然后迭代以构建查询。