كيف يمكنني العثور على فهرس سلسلة غير محددة في القائمة

StackOverflow https://stackoverflow.com/questions/984982

  •  13-09-2019
  •  | 
  •  

سؤال

إنه أفهم أنه إذا أردت الحصول على معرف عنصر في قائمة، يمكنني القيام بذلك:

private static void a()
{
    List<string> list = new List<string> {"Box", "Gate", "Car"};
    Predicate<string> predicate = new Predicate<string>(getBoxId);
    int boxId = list.FindIndex(predicate);
}

private static bool getBoxId(string item)
{
    return (item == "box");
}

ولكن ماذا لو كنت أرغب في جعل المقارنة ديناميكية؟ لذا بدلا من التحقق من ذلك ما إذا كان العنصر == "المربع"، أريد أن أبعز في سلسلة تم إدخاله للمستخدم للمندوب، ثم تحقق مما إذا كان العنصر == SearchString.

هل كانت مفيدة؟

المحلول

يعد استخدام الإغلاق الذي تم إنشاؤه بالمترجم عبر طريقة مجهولة أو Lambda طريقة جيدة لاستخدام قيمة مخصصة في تعبير مسند.

private static void findMyString(string str)
{
    List<string> list = new List<string> {"Box", "Gate", "Car"};
    int boxId = list.FindIndex(s => s == str);
}

إذا كنت تستخدم .NET 2.0 (لا Lambda)، فسوف يعمل هذا أيضا:

private static void findMyString(string str)
{
    List<string> list = new List<string> {"Box", "Gate", "Car"};
    int boxId = list.FindIndex(delegate (string s) { return s == str; });
}

نصائح أخرى

يمكنك فقط القيام به

string item = "Car";
...

int itemId = list.FindIndex(a=>a == item);
string toLookFor = passedInString;
int boxId = list.FindIndex(new Predicate((s) => (s == toLookFor)));
List <string>  list= new List<string>("Box", "Gate", "Car");
string SearchStr ="Box";

    int BoxId= 0;
        foreach (string SearchString in list)
        {
            if (str == SearchString)
            {
                BoxId= list.IndexOf(str);
                break;
            }
        }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top