Loogawa
Loogawa

Reputation: 389

Replace all values in IQueryable with string based on results using LINQ

I have an IQueryable I selected from a database that contains a field called "NewValue". This field will either contain a 0, 1, or 2. I want to replace the value with a string based of which number it is.
i.e 0 = "Active". I know IQueryables aren't used to change values mostly just for querying but I need to use it in the next line to add to the ViewModel

var AssessmentList = assessment                    
.Select(p => new LogManagementViewModel
{
   newValue = p.NewValue,
});

How can I change all the values in assement.NewValue to a string?

Upvotes: 0

Views: 2817

Answers (5)

Snowbear
Snowbear

Reputation: 17274

var values = new [] {"StrValue1", "StrValue2", "StrValue"};

var AssessmentList = assessment                    
    .AsEnumerable()
    .Select(p => new LogManagementViewModel
        {
            newValue = values[p.NewValue],
        });

Upvotes: 1

BrokenGlass
BrokenGlass

Reputation: 160912

Easiest and cleanest would be with a mapping method:

string MapToString(int value)
{
    //..
}

var AssessmentList = assessment                    
.Select(p => new LogManagementViewModel
{
   NewValue = MapToString(p.NewValue),
});

Upvotes: 1

Jon
Jon

Reputation: 437386

var dictionary = new Dictionary<int, string>
{
    { 0, "Active" },
    { 1, "Inactive" },
    // etc
};

var AssessmentList = assessment                    
.Select(p => new LogManagementViewModel
{
    newValue = dictionary[p.NewValue],
});

This would work for mapping between other types as well.

Upvotes: 2

CodingGorilla
CodingGorilla

Reputation: 19842

I would make a constructor overload in your LogManagementViewModel that does that work for you, something like this:

public LogManagementViewModel(int NewValue)
{
  switch(NewValue)
  {
      case 0:
         this.NewValue = "Active";
         break;
       // etc...
  }
}

IMO, this places the logic in it's proper place, let the your view model translate it as it should be, it's not the responsibility of your LINQ/Database queries.

Upvotes: 0

Joe Enos
Joe Enos

Reputation: 40403

One way:

Add a new computed property onto your class (assuming you have a partial class outside of any generated code). Then that computed class can do the translation however it needs to. Your view model can reference this computed value.

Upvotes: 0

Related Questions