Solved

How to check for a specific value in List<T> foreach loop

Posted on 2014-04-29
13
441 Views
Last Modified: 2014-04-30
Hello Experts,

Need help checking for a specific value in List<T> foreach loop. If there is specific value then display a specific string value.

For example, how do I…

If (value.something_2 == “Null”)
{
    value.something_2 == “.“;
}
Elseif (value.something_2 == “ “)
{
    value.something_2 == “0”;
}

Open in new window



How would I incorporate the "If" statement within the “foreach” loop?

See code

protected void MyReport(string filename, IMyRepository repository)
        {

            using (FileStream fileStream = new FileStream(Server.MapPath(@"~/Includes/") + filename, FileMode.Create))

            {

                using (StreamWriter writer = new StreamWriter(fileStream))
                {

                    List<Report> _report = repository.GetMyReport().ToList();

                    foreach (var value in _report)
                    {


String row01 = String.Format("{0, -10}{1, 23}{2, 120}{3, 8}", value.somthing_1, values.something_2, value.something_3);

String row02 = String.Format("{0, -10}{1, 23}{2, 120}{3, 8}", value.somthing_4, values.something_5, value.something_6);



Writer.WriteLine(row01);
Writer.WriteLine(row02);


    }


   }
      writer.Close();
}
}

Open in new window


When I write the "if" statment within the foreach loop I get an error...
"only assignment expression can be used as statement".
and I get other errors if I re-write the "If" statement.

Thank you for your help.
0
Comment
Question by:iNetBlazer
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
  • 3
13 Comments
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 40029757
Does this do what you want?

                    foreach (var value in _report)
                    {


Writer.WriteLine(String.Format("{0, -10}{1, 23}{2, 120}{3, 8}", value.somthing_1, values.something_2, value.something_3));
Writer.WriteLine(String.Format("{0, -10}{1, 23}{2, 120}{3, 8}", value.somthing_4, values.something_5, value.something_6));


    }
0
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 40029792
Sorry, ignore that previous comment.  I misunderstood what you wanted.

instead of:
 
foreach (var value in _report)
                    {

Open in new window

you would be better to loop through this way (because the compiler doesn't like the object in the foreach being modified whilst in the foreach loop):
for(int i = 0; i < _report.Length; i++)
{
  var value = _report[i];

Open in new window

If the 'T' is a reference type changing the value inside the object will change the value in the original object.  Is that what you wanted?  If not then you need to extract the individual contents into local strings and modify those.
0
 

Author Comment

by:iNetBlazer
ID: 40029856
Ok, Keeping in mind that the values are of type decimal and is returned by SQL Db via EntityFramework.  There are values within the Db that have "Null" and/or Whitespace.  I need the check for this and if the value have "Null" then display "." is the value has Whitespace then display "0".
0
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 
LVL 44

Expert Comment

by:AndyAinscow
ID: 40029871
string s2;
if (value.something_2 == “Null”)
{
    s2 == “.“;
}
else if (value.something_2 == “ “)
{
    s2 == “0”;
}
else
  s2 = value.something_2.ToString();
0
 

Author Comment

by:iNetBlazer
ID: 40029941
Get error...

Operator '==' cannot be applied to operands of type 'decimal?' and 'string'
0
 
LVL 44

Accepted Solution

by:
AndyAinscow earned 250 total points
ID: 40030034
OK, that seems to be the value can never be " ", which makes it fractionally simpler code:

string s2;
if (value.something_2 == “Null”)
{
    s2 == “.“;
}
else
  s2 = value.something_2.ToString();
0
 
LVL 11

Expert Comment

by:Salim Fayad
ID: 40031387
You should use Report instead of var in your foreach loop. So, instead of:
foreach (var value in _report)

Open in new window


You should write it:
foreach (Report value in _report)

Open in new window

0
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 40031403
@The_eagle, why should that have an effect?  There is no difference in those two foreach statements.


Excerpt from:  http://msdn.microsoft.com/en-us/library/bb383973.aspx

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:

var i = 10; // implicitly typed
int i = 10; //explicitly typed
0
 
LVL 11

Assisted Solution

by:Salim Fayad
Salim Fayad earned 250 total points
ID: 40031408
By the way, there is another bug, you cannot assign with the "==", you should use one equal:
if (value.something_2 == “Null”)
{
    s2 == “.“;
}
else if (value.something_2 == “ “)
{
    s2 == “0”;
}
else
  s2 = value.something_2.ToString(); 

Open in new window


should be:
if (value.something_2 == “Null”)
{
    s2 = “.“;
}
else if (value.something_2 == “ “)
{
    s2 = “0”;
}
else
  s2 = value.something_2.ToString(); 

Open in new window

0
 

Author Comment

by:iNetBlazer
ID: 40031964
@Guru and @Ace,

You both pointed me in the right direction structuring the "If" statement.  Refer to the below code as the solution resulting from both your suggestions.

In referencing the code keep in mind the Db has a column of type decimal and it can have a value or Null.

foreach (var value in report)
{
  string dot = ".";
  string reportValue;

if (!value.someDecimalValue)
{
  reportValue = dot;
}
else
{
  reportValue = value.someDecimalValue.ToString();
}

//Other code here

}

Open in new window



Thank you for your help.
0
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 40031978
I'm not clear.
Are you still getting errors?
Is something not working the way you expect it to?
0
 
LVL 11

Expert Comment

by:Salim Fayad
ID: 40031984
It depends how are you filling the List<Report> from the database. If this decimal property in C# is nullable, then you can check if null
value.someDecimalValue == null

Open in new window

, if not, then you might need to check it with the
Decimal.MinValue

Open in new window

, so it becomes
value.someDecimalValue == Decimal.MinValue

Open in new window

0
 

Author Comment

by:iNetBlazer
ID: 40031991
Correction... I forgot to wright "HasValue"

foreach (var value in report)
{
  string dot = ".";
  string reportValue;

if (!value.someDecimalValue.HasValue)
{
  reportValue = dot;
}
else
{
  reportValue = value.someDecimalValue.ToString();
}

//Other code here

}

Open in new window

0

Featured Post

Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …

688 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question