2014-03-07 221 views
0

嗨我收到以下錯誤與我的Linq查詢。Linq將字符串轉換爲列表

Cannot implicitly convert type 'System.Collections.Generic.List<string>' 
to 'System.Collections.Generic.List<CTS.Domain.OCASPhoneCalls>' 

我知道它是什麼意思,但我不確定如何解決它。有人可以幫我查詢嗎?我對linq真的很陌生。

public List<OCASPhoneCalls> getPhoneLogs2() 
{ 
    using (var repo = new OCASPhoneCallsRepository(new UnitOfWorkCTS())) 
    { 
     List<OCASPhoneCalls> phone = repo.AllIncluding(p => p.OCASStaff) 
      .Where(y => y.intNIOSHClaimID == null) 
      .Select(w => w.vcharDiscussion.Substring(0, 100) + "...") 
      .ToList();     
     return phone; 
    } 
} 
+0

您選擇'名單'但你宣告'名單' –

回答

3

您選擇List<string>但你宣告List<OCASPhoneCalls>,我想你想縮短vcharDiscussion

List<OCASPhoneCalls> phones = = repo.AllIncluding(p => p.OCASStaff) 
    .Where(p => p.intNIOSHClaimID == null) 
    .ToList(); 
phones.ForEach(p => p.vcharDiscussion = p.vcharDiscussion.Length > 100 ? 
     p.vcharDiscussion.Substring(0, 100) + "..." : 
     p.vcharDiscussion); 
return phones; 

編輯:「我得到一個空的錯誤。 vcharDiscussion快到了空

然後,你需要檢查:

phones.ForEach(p => p.vcharDiscussion = 
    p.vcharDiscussion != null && p.vcharDiscussion.Length > 100 ? 
    p.vcharDiscussion.Substring(0, 100) + "..." : 
    p.vcharDiscussion ?? ""); 
+0

我確實想縮短vcharDiscussion並將...添加到最後。 – hollyquinn

+0

@hollyquinn:那麼這應該工作。你需要迭代它們來修改屬性。 –

+0

我在返回手機上收到以下錯誤消息。不能隱式地將類型'System.Collections.Generic.List '轉換爲'System.Collections.Generic.List ' – hollyquinn

6

您選擇一個屬性與

.Select(w => w.vcharDiscussion.Substring(0, 100) + "...") 

這將返回你IEnumerable<string>,並呼籲ToList將返回你List<string>List<OCASPhoneCalls>

如果要返回格式的字符串,然後你的方法的返回類型應該是List<string>像:

public List<string> getPhoneLogs2() 
{ 
    using (var repo = new OCASPhoneCallsRepository(new UnitOfWorkCTS())) 
    { 
     List<string> phone = repo.AllIncluding(p => p.OCASStaff) 
      .Where(y => y.intNIOSHClaimID == null) 
      .Select(w => w.vcharDiscussion.Substring(0, 100) + "...") 
      .ToList();     
     return phone; 
    } 
} 
+0

我相當肯定,他想要返回對象,但是如果需要的話縮短文本屬性 –

+0

@TimSchmelter,嗯,在這種情況下,OP必須先迭代,然後在你的答案中修改該字段+1 – Habib

+0

@TimSchmelter我使用這些數據來填充一個GridView,它現在說GridView中的其他列不存在,錯誤消息是DataBinding:'System.String'不包含適當的ty名稱爲'dtmDateCalled'。我必須在我的查詢中選擇那些嗎?你能告訴我如何解決這個問題嗎?謝謝。 – hollyquinn

0
`.Select(w => w.vcharDiscussion.Substring(0, 100) + "...")` 

,因爲選擇它的預測,它會返回字符串列表,你的方法,希望返回

List<OCASPhoneCalls>