hollyquinn
hollyquinn

Reputation: 652

Linq Converting String to List

Hi I am getting the following error with my Linq query.

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

I know what it means, but I'm unsure how to fix it. Can someone help me with my query? I'm really new to 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;
    }
}

Upvotes: 0

Views: 91

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460108

You are selecting a List<string> but you are declaring a List<OCASPhoneCalls>, i assume you want to shorten the 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;

Edit: "I'm getting a null error. vcharDiscussion is coming up null"

Then you need to check that:

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

Upvotes: 3

BRAHIM Kamel
BRAHIM Kamel

Reputation: 13765

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

because select it's projection and it will return a list of string and your method expect to return

List<OCASPhoneCalls>

Upvotes: 0

Habib
Habib

Reputation: 223257

You are selecting a single property with

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

This would return you IEnumerable<string> and calling ToList would return you List<string> NOT List<OCASPhoneCalls>.

If you are returning formatted strings then your method return type should be List<string> like:

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;
    }
}

Upvotes: 6

Related Questions