-1

I am trying to use getThingFromID to return an object in a Thing[] array with the specified ID. How do I do this in c#?

class Thing
{
    public int _id { get; set; }

    public Thing(int id)
    {
        _id = id;
    }

    Thing getThingFromID(int id)
    {
        
    }
}

class Program
{
    static void Main(string[] args)
    {

        Thing[] arr = new Thing[3];
        arr[0] = new Thing(44);
        arr[1] = new Thing(55);
        arr[2] = new Thing(66);

        arr.getThingFromID(55);
    {
{
  • First of all, `arr.getThingFromID` won't compile. You need to either have the `getThingFromID` take a `Thing[]` argument or convert it to an extension method. As to what goes into the body of the method, you may start with something like `arr.FirstOrDefault(t => t._id == id);`. As a side note, you should stick to the C# [naming convention](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions). – 41686d6564 stands w. Palestine Jun 27 '21 at 17:21
  • Putting the `getThingFromID()` method in the `Thing` class doesn't seem useful to me. The `Thing` class doesn't know anything about the `arr` array. That said, as far as the actual question goes, `arr.FindIndex(x => x._id == id)` will get you the index of the `arr` element where the property `_id` is equal to `id`. See duplicate. – Peter Duniho Jun 27 '21 at 17:21
  • Hi, You will require the use of 'Extension' methods to achieve this. You can check this answer for reference: https://stackoverflow.com/questions/1183083/is-it-possible-to-extend-arrays-in-c/1183291 – Suyash Gaur Jun 27 '21 at 17:21
  • 1
    Why don't you use a dictionary? look at this code: https://dotnetfiddle.net/XQDPqe – Carlos Garcia Jun 27 '21 at 17:22
  • @CarlosGarcia thats a good idea – emptyPigeon Jun 27 '21 at 17:25

1 Answers1

0

If you insist on syntax like

  arr.getThingFromID(55);

you can implement an extension method:

  using System.Linq;

  ...

  static class ThingExtensions {

    public static Thing getThingFromID(this IEnumerable<Thing> source, int id) {
      if (null == source)
        return null;

      return source
        .FirstOrDefault(item => item?._id == id); 
    }  
  }

The call will be as if arr itself has getThingFromID method:

  Thing result = arr.getThingFromID(55);

If you want to keep Thing getThingFromID(int id):

class Thing
{
    //TODO: I suggest put "private set" instead of "set"
    public int _id { get; set; }

    public Thing(int id)
    {
        _id = id;
    }

    public static Thing getThingFromID(int id, IEnumerable<Thing> source)
    {
        if (null == source)
            return null;

        return source
            .Where(item => item != null)
            .FirstOrDefault(item => item._id == id); 
    }
}

But you have to call it as

Thing result = Thing.getThingFromID(55, arr); 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215