foreach loop with custom class list not printing correct value

print list in java without loop
how to print a list java
java print arraylist of objects
print elements of arraylist java
for-each loop
how to print arraylist in java using for loop
how to print array without loop in java
how to store list values in string in java

I have a foreach loop that i'm trying to iterate through a list attached to a class

public class FInfo
{
    public string FilePath { get; set; }
    public string MD5Hash { get; set; }   
}

it's small class right now but i may add to it later.

However i'm not sure how to access it

private void DirOut(string sDir)
    {

        try
        {
            string[] array1 = Directory.GetDirectories(sDir);
            for (int i1 = 0; i1 < array1.Length; i1++)
            {
                string d = array1[i1];
                dirC++;

                outliststring.Add(new FInfo {FilePath = d, MD5Hash = "N/A"});

                try
                {

                    String md5string; 
                    String[] array = Directory.GetFiles(d, txtFile.Text);
                    for (int i = 0; i < array.Length; i++)
                    {
                       string f = array[i];


                       outliststring.Add(new FInfo { FilePath = f, MD5Hash = "N/A" });

                    }
                }
                catch (System.Exception excpt)
                {
                    Console.WriteLine(excpt.Message);
                }
                DirOut(d);
            }
        }
        catch (System.Exception excpt)
        {
            Console.WriteLine(excpt.Message);

        }

}

This code adds the items to the list.

then I've using this code to write it to a text file.

 Stream fileStream2 = sfd.OpenFile();
        using (StreamWriter sw =new StreamWriter(fileStream2))
        {
            foreach (FInfo fp in outliststring)
            {
                sw.WriteLine(DateTime.Now.ToString() + ":- " + fp);


            }

            sw.Close();
            fileStream2.Close();

        }

However this just write the time and date then FInfo. Can someone explain how i add both the values to the sw.writeline command.

Thanks

Just use it like:

foreach (FInfo fp in outliststring)
{
  sw.WriteLine(DateTime.Now.ToString() + ":- " + fp.FilePath +" "+ fp.MD5Hash );
}

How to print out all the elements of a List in Java?, public class ListExample { public static void main(String[] args) { List<Model> models Since Java 8, List inherits a default "forEach" method which you can combine with If you are using any custom object in your list, say Student , you need to array; merely setting the value of an element is not a structural modification. C#‘s foreach loop makes it easy to process a collection: there's no index variable, condition, or code to update the loop variable. Instead the loop variable is automatically set to the value of each element. That also means that there's no index variable with foreach. Luckily there are several ways to get one.

I'd say the best approach would be to override ToString() in FInfo:

public override string ToString()
{
    return $"{FilePath}\t{MD5Hash}";
}

The method WriteLine automatically calls ToString() on your fp object to combine it with the rest of the string for the output. Right now your code is just using the ToString() defined on a base class (most likely object) whose default behavior is just to print the name of the class, as you've observed.

An alternative approach is to just use the properties directly:

sw.WriteLine(DateTime.Now.ToString() + ":- " + $"{fp.FilePath}\t{fp.MD5Hash}" );

Java Loop Through List, statement in many other languages, especially array programming languages, does not have any particular order. C# provides an easy to use and more readable alternative to for loop, the foreach loop when working with arrays and collections to iterate through the items of arrays/collections. The foreach loop iterates through each item, hence called foreach loop. Before moving forward with foreach loop, visit: C# for loop; C# arrays; C# collections

Try to override ToString method in your FInfo class:

public class FInfo
{
    public string FilePath { get; set; }
    public string MD5Hash { get; set; }   
    public override string ToString() => $"FilePath:{FilePath}, MD5Hash:{MD5Hash}";
}

Foreach loop, Along with these enhancements to the language, all Collection classes were thus allowing Collection classes to be iterable using the foreach loop. of the underlying collection; however, it may also return an instance of a custom Iterator. (see Chapter 6), which prints the value of each element within the myPortfolio  Of course this does not return a List<string>, you could tack a ToList() on the end. Or you could use ConvertAll like this: stringList.ConvertAll(element => element + " modified"); and of course to make other references to stringList point to the new list: stringList = stringList.ConvertAll(element => element + " modified"); Hogan

In C# there are multiple places where the ToString Method of a object is called where the programmer didn't explicitly have to say so. In your case on the line sw.WriteLine(DateTime.Now.ToString() + ":- " + fp); the fp.ToString(); is called. You can now either do as @rory.ap said override the ToString method or use string interpolation like so:

sw.WriteLine($"{DateTime.Now}:- {fp.FilePath}\t{fp.MD5Hash}");

Edit: String interpolation is a really neat feature in C#, you tell the compiler that it's a interpolated string by placing a $ before the quotation marks, and then within in the string you can use { and } (curly braces) to put code into that return or are a string This is a really powerful feature and replaces now outdated methods like string concatenation (what you're using with the +s) and string.Format() method

Here Is 4 Ways To Print ArrayList Elements In Java, The Map values() method returns the Collection of map values; in this case, can be used to iterate a StockPortfolio instance and print each Stock: myPortfolio. This method also uses a foreach loop to iterate through the input List. not expose the internal implementation details of our class (the portfolio map). this allows  If you do not implement IEnumerator, you cannot cast the return value from the GetEnumerator method of IEnumerable to the IEnumerator interface. In summary, the use of IEnumerable requires that the class implement IEnumerator. If you want to provide support for foreach, implement both interfaces. Step by step example

Java 9 Recipes: A Problem-Solution Approach, Here the example shows how we can iterate through elements of an array using the standard for loop. class ForLoop { public static void main(String[] args)  Arrays Basic C# C# Console C++ Class Collection Conditional Statement Database Do While Loop Foreach Statement For Loop General If Else Statement Java Library Linq List Loops / Iteration Statement Methods Programming Languages Pseudocode Examples Python 3 SQL Stack String Methods Switch Statement While Loop Windows Form WPF Form

Java 8 Recipes, In this article, we will learn about foreach loops (an alternative to for loop) and how to use them with arrays Sort ArrayList of Custom Objects By Property Here iterable-item can be an array or a class of collection. Inside the body of loop, the value of ch is printed. This program computes the sum of elements in a List. Foreach a list of objects. You named the collection ObjectoAOcultar but in the foreach loop you are using ObjetoAOcultar. Correct - the builtin foreach works

Java for-each Loop (Enhanced for Loop), enhanced for-loop does not work with Iterator , so the following won't even compile: The error: BadColony.java:36: foreach not applicable to expression type Actually, to be more correct, you can use a generic T , allowing  Difference between for loop and foreach loop: for loop executes a statement or a block of statement until the given condition is false. Whereas foreach loop executes a statement or a block of statements for each element present in the array and there is no need to define the minimum or maximum limit. In for loop, we iterate the array in both

Comments
  • @mjwills it prints a line in the text file with the current date and time and where fp should be the filepath and then a hash number (not implemented yet) it just has Finfo.
  • Thank you it's so simple i should have known
  • Why is this a better approach than accessing the class properties? I'm genuinely curious because it looks like a bit overkill to me, but it has to be a good reason since several people answered the same.
  • Nitpicky criticisms: Technically fp.FilePath and fp.MD5Hash aren't fields but properties ;). Also I'd would make more sense to wrap the whole sw.Writeline parameter in a interpolated string and not mix and match concatenation with it
  • @ikerbera the override Method is in certain cases better, like if you want to print the same thing over and over so instead of doing sw.WriteLine(DateTime.Now.ToString() + ":- " + $"{fp.FilePath}\t{fp.MD5Hash}" ); you can just do sw.WriteLine(fp); which is a lot more concise. But for one offs I recommend using string interpolation
  • @ikerbera -- It's always a good idea to override ToString() since you never know where it's going to be used/needed. It's better to control the string your code supplies when something calls that method, because it gets called a lot in places you wouldn't necessarily expect. For example, in the debugger, when you're looking at the variable it will print the results of ToString(). This is helpful when you have a collection of things and want to be able to quickly see which is which.
  • And doing that doesn't preclude using the other approach I outlined.