Mr.Bobo Haha
Mr.Bobo Haha

Reputation: 141

how to format a string in linq

im having problem with my string of time.. i wanted to format it so that it will display a more neat design.. can anyone help me with this one

here's my code:

 ViewBag.startTime = 
 (from a in test
  where a.ID == clientCustomerPositionShiftnfo.ID
  select new{ a.StartTime})
  .AsEnumerable()
  .Select(a => a.StartTime != "Anytime"
  ? Convert.ToDateTime(a.StartTime).ToString("HH:mm:ss")
  : a.StartTime.Trim());

In my view:

    <input type="text" id="txtStartTime" name="txtStartTime" class="inputLong"
value="@ViewBag.startTime" disabled="disabled"/>

Upvotes: 1

Views: 152

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149020

Try calling First after your query:

ViewBag.startTime = 
    (from a in test
     where a.ID == clientCustomerPositionShiftnfo.ID
     select a.StartTime)
    .AsEnumerable()
    .Select(t => t != "Anytime" ? Convert.ToDateTime(t).ToString("HH:mm:ss") : t)
    .First(); // or FirstOrDefault if your query might not return any results

Or perhaps more cleanly:

var startTime = 
    (from a in test
     where a.ID == clientCustomerPositionShiftnfo.ID
     select a.StartTime)
    .First(); // or FirstOrDefault if your query might not return any results
ViewBag.startTime startTime != "Anytime" 
    ? Convert.ToDateTime(startTime).ToString("HH:mm:ss") 
    : startTime;

Upvotes: 3

Related Questions