Home > Enterprise >  C# linkedlist find method throws error "cannot convert lambda expression to type 'Item
C# linkedlist find method throws error "cannot convert lambda expression to type 'Item

Time:01-04

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        LinkedList<Item> list = new LinkedList<Item>();

        // Add some items to the list
        list.AddLast(new Item { Id = 1, Name = "Item 1" });
        list.AddLast(new Item { Id = 2, Name = "Item 2" });
        list.AddLast(new Item { Id = 3, Name = "Item 3" });

        // Find an item by its id
        int idToFind = 2;
        LinkedListNode<Item> node = list.Find((Item x) => x.Id == idToFind);
        if (node != null)
        {
            Console.WriteLine("Found item: {0}", node.Value.Name);
        }
        else
        {
            Console.WriteLine("Item not found");
        }
    }
}

class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
}

I am searching for the reason why lambda is not allowed in Find method but same is working in FirstOrDefault?

CodePudding user response:

Find doesn't expect a lambda but an Item: https://learn.microsoft.com/dotnet/api/system.collections.generic.linkedlist-1.find?view=net-7.0.

So you'd need this:

LinkedListNode<Item> node = list.Find(myItem);

which is pretty unhandy when you want to search for an Item that satisfies a specific condition. That's where FirstOrDefault comes into play:

LinkedListNode<Item> node = list.FirstOrDefault(x => x.id == idToFind);

CodePudding user response:

I think the problem is in others List type instance you can use Find(Predicate<T> match) to get the item which you want. For example

var list = new List<string>().Find(x => x == "a");

This is because List<T> implement the method

public class List<T> 
{
    public T? Find(Predicate<T> match)
}

But now which you used is LinkedListNode<T> the Find() implemention in it is

public class LinkedList<T>
{
    public LinkedListNode<T>? Find(T value)
}

So that's why you got a complile error.

  •  Tags:  
  • c#
  • Related