如果在Linq中不为null则修剪字符串

时间:2015-01-13 06:22:27

标签: c# linq linq-to-sql

我遇到了这个重复出现的问题,我正在使用遗留数据库和linq to sql,它使用固定长度的char数据类型。

当我返回字符串时,它总是在末尾有填充,如果我想在select语句中连接两个字符串,我总是需要先检查是否为null,例如:

 return (from person in personRepository.Get(p => p.FIRSTNAME.StartsWith(firstName)
         || p.SURNAME.StartsWith(surname) || p.DOB == dob)
                select new PersonSearchModel
                {
                    FullUserName = (person.SURNAME ?? "").Trim() + ", " 
                                 + (person.FIRSTNAME ?? "").Trim() + " " 
                                 + (person.MIDDLENAME ?? "").Trim()
                }).ToList();

有更好的方法吗?我可以在数据库上下文中有一些东西来自动修剪字符串吗?

1 个答案:

答案 0 :(得分:1)

我最后更改了t4模板,以便类生成自动修剪的字符串,如果它们不为null,则返回null。

 public string Property(EdmProperty edmProperty)
{
    string type = _typeMapper.GetTypeName(edmProperty.TypeUsage);
    string propertyName = _code.Escape(edmProperty);

    if(type == "string"){

    return string.Format(
        CultureInfo.InvariantCulture,
        "private {1} _{6}; {5} \t{0} {1} {2} {{ {5}\t\t{3}get{{return _{6} == null ? null : _{6}.Trim();}} {5}\t\t{4}set{{ _{6} = value;}} }}",
        Accessibility.ForProperty(edmProperty),
        type,
        propertyName,
        _code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
        _code.SpaceAfter(Accessibility.ForSetter(edmProperty)),
        Environment.NewLine,
        propertyName.ToLower()
        );

    }else{
    return string.Format(
        CultureInfo.InvariantCulture,
        "{0} {1} {2} {{ {3}get; {4}set; }}",
        Accessibility.ForProperty(edmProperty),
        _typeMapper.GetTypeName(edmProperty.TypeUsage),
        _code.Escape(edmProperty),
        _code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
        _code.SpaceAfter(Accessibility.ForSetter(edmProperty)));
        }
}