2010-12-03 19 views
1

我編寫了此SQL Server select語句,只返回204個字符,並在該行最多包含204個字符的情況下追加...。如何使用linq to sql返回文本的部分字符串

SELECT Name, Active, Image, CASE WHEN LEN(Description) <= 204 THEN Description ELSE LEFT (Description , 204) + '...' END AS 'Short Description' FROM Brands 

我該如何完成這個linq代碼來做同樣的事情?

var query = db.Brands.Select(p=> new{ 
     Brand =p, 
     p.Description.Length <-- I believe this is a starting point?> 
    }); 

回答

2

好,直譯是:

var query = db.Brands.Select(p => new { 
     Brand = p, 
     Description = p.Description.Length < 204 
          ? p.Description 
          : p.Description.Substring(0, 204) + "..." 
    }); 

但我會感到驚訝,如果工作...

它是絕對至關重要的,你做這個SQL一邊,而不是客戶?例如,這工作:

var query = db.Brands 
       .AsEnumerable() 
       .Select(p => new { 
     Brand = p, 
     Description = p.Description.Length < 204 
          ? p.Description 
          : p.Description.Substring(0, 204) + "..." 
    }); 
+0

是最好的方式做到這一點?我只是爲了一個我想要完成的例子而包含SQL代碼。 – 2010-12-03 22:24:55

0

正確的方式來寫它如下:

var query = db.Brands.Select(p=> new{ 
     Brand =p, 
     c= p.Description.Length < 204 ? p.Description 
           : p.Description.Substring(0, 204) + "..." 
    }); 
相關問題