第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我可以為 IEnumerable.Any 方法動態(tài)添加參數(shù)到 LINQ 查詢嗎?

我可以為 IEnumerable.Any 方法動態(tài)添加參數(shù)到 LINQ 查詢嗎?

C#
冉冉說 2022-12-31 10:51:26
我創(chuàng)建了一個方法,它接受一個動態(tài)列表、一個對象和兩個參數(shù)名稱。我想使用 Enumerable.Any 方法返回一個布爾值,該方法具有基于傳遞給方法的參數(shù)名稱的匹配條件。public static bool CheckDuplicate(List<T> list, Object obj, string param1, string param2){    return list.Any(item => item.pararm1 = obj.param1 && item.param2 = obj.param2);}我想根據(jù)動態(tài)提供的條件找到與 obj 對象匹配的值的項目。
查看完整描述

2 回答

?
拉莫斯之舞

TA貢獻1820條經(jīng)驗 獲得超10個贊

似乎您想要的是比較通過成員變量的名稱訪問的成員變量。這稱為反射。這是我的解決方案:


首先添加一個擴展方法來幫助我們通過名稱獲取成員變量(來自this SO answer):


static class Extension

{

    public static object GetPropValue(this object src, string propName)

    {

        return src.GetType().GetProperty(propName).GetValue(src, null);

    }

}

然后,您的功能將是:


public static bool CheckDuplicate<T>(IEnumerable<T> list, object obj, string param1, string param2)

    {

        return list.Any(item =>

        item.GetPropValue(param1).Equals(obj.GetPropValue(param1)) &&

        item.GetPropValue(param2).Equals(obj.GetPropValue(param2))

        );

    }

我用這個測試了這個功能。它打印True:


static void Main(string[] args)

    {

        var theList = Enumerable.Range(0, 10).Select(i => new Tuple<int, int>(i, i + 1));

        Console.WriteLine(CheckDuplicate(theList, new { Item1 = 5, Item2 = 6 }, "Item1", "Item2"));

        Console.ReadKey();

    }

但是,對于生產(chǎn)中的使用,您可能希望確保param1和確實存在,并且還請查找并考慮和param2之間的差異。注意從中返回的值是裝箱的可能很有用。.Equals()==GetPropValue()


查看完整回答
反對 回復(fù) 2022-12-31
?
慕絲7291255

TA貢獻1859條經(jīng)驗 獲得超6個贊

考慮創(chuàng)建一個類似 LINQ 的擴展方法WhereAll,它執(zhí)行Where作為參數(shù)給出的所有謂詞:


static IEnumerable<TSource> WhereAll<TSource>(this IEnumerable<TSource> source

   IEnumerable<Func<TSource, bool>> predicates)

{

    // TODO: exception if source / predicates null


    // return all source elements that have a true for all predicates:

    foreach (var sourceElement in source)

    {

        // check if this sourceElement returns a true for all Predicates:

        if (predicates.All(predicate => predicate(sourceElement))

        {

             // yes, every predicate returns a true

             yield return sourceElement;

        }

        // else: no there are some predicates that return false for this sourceElement

        // skip this element

 }

用法:


List<Person> persons = ...

// Get all Parisians with a Name that were born before the year 2000:

var result = persons.WhereAll(new Func<Person, bool>[]

    {

         person => person.Name != null,

         person => person.BirthDay.Year < 2000,

         person => person.Address.City == "Paris",

    });


查看完整回答
反對 回復(fù) 2022-12-31
  • 2 回答
  • 0 關(guān)注
  • 90 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號