Home > Back-end >  List<T> C# find specific line
List<T> C# find specific line

Time:11-24

I was reading this https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.find?view=net-6.0 and try it as the example code:

using System;
using System.Collections.Generic;
// Simple business object. A PartId is used to identify a part
// but the part name can change.
public class Part : IEquatable<Part>
{
    public string PartName { get; set; }
    public int PartId { get; set; }

    public override string ToString()
    {
        return "ID: "   PartId   "   Name: "   PartName;
    }
    public override bool Equals(object obj)
    {
        if (obj == null) return false;
    Part objAsPart = obj as Part;
    if (objAsPart == null) return false;
    else return Equals(objAsPart);
}
public override int GetHashCode()
{
    return PartId;
}
public bool Equals(Part other)
{
    if (other == null) return false;
    return (this.PartId.Equals(other.PartId));
}
// Should also override == and != operators.

}
public class Example
{
public static void Main()
{
    // Create a list of parts.
    List<Part> parts = new List<Part>();

    // Add parts to the list.
    parts.Add(new Part() { PartName = "crank arm", PartId = 1234 });
    parts.Add(new Part() { PartName = "chain ring", PartId = 1334 });
    parts.Add(new Part() { PartName = "regular seat", PartId = 1434 });
    parts.Add(new Part() { PartName = "banana seat", PartId = 1444 });
    parts.Add(new Part() { PartName = "cassette", PartId = 1534 });
    parts.Add(new Part() { PartName = "shift lever", PartId = 1634 }); ;

    // Write out the parts in the list. This will call the overridden ToString method
    // in the Part class.
    Console.WriteLine();
    foreach (Part aPart in parts)
    {
        Console.WriteLine(aPart);
    }

    // Check the list for part #1734. This calls the IEquatable.Equals method
    // of the Part class, which checks the PartId for equality.
    Console.WriteLine("\nContains: Part with Id=1734: {0}",
        parts.Contains(new Part { PartId = 1734, PartName = "" }));

    // Find items where name contains "seat".
    Console.WriteLine("\nFind: Part where name contains \"seat\": {0}",
        parts.Find(x => x.PartName.Contains("seat")));

    // Check if an item with Id 1444 exists.
    Console.WriteLine("\nExists: Part with Id=1444: {0}",
        parts.Exists(x => x.PartId == 1444));

    /*This code example produces the following output:

    ID: 1234   Name: crank arm
    ID: 1334   Name: chain ring
    ID: 1434   Name: regular seat
    ID: 1444   Name: banana seat
    ID: 1534   Name: cassette
    ID: 1634   Name: shift lever

    Contains: Part with Id=1734: False

    Find: Part where name contains "seat": ID: 1434   Name: regular seat

    Exists: Part with Id=1444: True
     */
}
}

now I want to know if there is a way to assign a special line into a text box or something like that? sorry for my bad English I will say as an example. in this part of codes we have

parts.Add(new Part() { PartName = "crank arm", PartId = 1234 });
    parts.Add(new Part() { PartName = "chain ring", PartId = 1334 });
    parts.Add(new Part() { PartName = "regular seat", PartId = 1434 });
    parts.Add(new Part() { PartName = "banana seat", PartId = 1444 });
    parts.Add(new Part() { PartName = "cassette", PartId = 1534 });
    parts.Add(new Part() { PartName = "shift lever", PartId = 1634 }); ;

now I want to assign PartName into a textbox or string where the id is 1634 can someone tell me where can I get something like that? in this line

      // Find items where name contains "seat".
Console.WriteLine("\nFind: Part where name contains \"seat\": {0}",
    parts.Find(x => x.PartName.Contains("seat")));

it will check if partname contains "seat" exists and the output is

ID: 1434 Name: regular seat

the problem is I don't want the whole part to have, i want just PartName or PartID like : "1434", only this. not even "ID: 1434". i hope you guys understand me, i try my best :-( sorry for my bad English again. thanks

CodePudding user response:

Use linq:

var myPartName = parts.Where(p => p.PartId == 1432).Select(p => p.PartName).FirstOrDefault();

This will return the first partName with the given ID, or null if non exist.

You could also consider converting the list to a dictionary with the partId as key, this would give faster & easier lookup:

var partDict = parts.ToDictionary(p => p.PartId, p => p);
var myPartName = parts[1432].PartName; // will throw if id does not exist, use TryGet for a safer version

CodePudding user response:

At the moment the Find returns the whole object and the ToString() is called by default to display this as a string value.

If you just want the PartId to be shown then you can do this:

Console.WriteLine("\nFind: Part where name contains \"seat\": {0}",
                    parts.Find(x => x.PartName.Contains("seat"))?.PartId );

You can instead use PartName or any other property of Part

If you want something more complex then you can create a new method in the Part class and call that.

public class Part : IEquatable<Part>
{
    public string PartName { get; set; }
    public int PartId { get; set; }

    public override string ToString()
    {
        return "ID: "   PartId   "   Name: "   PartName;
    }

    public string AlternativeToString()
    {
        return this.PartId   " "   this.PartName;
    }

  //rest stays the same
}

And call it like this

Console.WriteLine("\nFind: Part where name contains \"seat\": {0}",
                    parts.Find(x => x.PartName.Contains("seat"))?.AlternativeToString() );
  • Related