开发者

How to replace lambda written in Where clause of Linq with equivalent delegate

开发者 https://www.devze.com 2023-01-16 18:23 出处:网络
I have an Query expression that uses a predicate type and lambda expression. I am getting desired result with this. But I am not clear with how this expression is getting evaluated.

I have an Query expression that uses a predicate type and lambda expression. I am getting desired result with this. But I am not clear with how this expression is getting evaluated.

I tried to break this lambda expression by creating delegate and replacing condition under Where with delegate type.

If I have to rewrite the same thing with writing a delegate instead of anonymous type. What will be the syntax. How the delegate will be return for the same.

if (((DataTable)dgvAssignedRpm.DataSource).AsEnumerable()
    .Where(row => row.Field<long>("FK_RPM_BTN_SETTING_ID") == objRpmButtonHolder.RpmSettingId).Count()开发者_JS百科 > 1)
{
  List<DataRow> listPkgBtnSettings = SearchForExistingSettingId();
}


void MethodSignature(...) 
{ 
  ...  

  if (((DataTable)dgvAssignedRpm.DataSource).AsEnumerable()
    .Where(RowCondition)
  {
    List<DataRow> listPkgBtnSettings = SearchForExistingSettingId();
  }

  ...
}

// Where want a Func<T,bool> parameter 
// T is the first parameter type (DataRow here)
// bool represents the return value
bool RowCondition(DataRow row)
{
  return row.Field<long>("FK_RPM_BTN_SETTING_ID") == objRpmButtonHolder.RpmSettingId).Count() > 1
}


I assume the correct delegate replacement would be:

        if (((DataTable)dgvAssignedRpm.DataSource).AsEnumerable().Where(
            delegate(DataRow row) {
                return (row.Field<long>("FK_RPM_BTN_SETTING_ID") == objRpmButtonHolder.RpmSettingId.Count() > 1); 
            }))
        {
            List<DataRow> listPkgBtnSettings = SearchForExistingSettingId();
        }

But it's morning for me, so forgive me if I'm a bit off.

What the where desires is to give a DataRow as a parameter and a bool to return. You could just about fill in anything in the lambda or delegate, as long as it matches these requests.

To your question why it requests Func<> and how it works. The statement you're using is LINQ, so I found you a reference regarding this which can probably explain it better than me: http://blogs.msdn.com/b/mirceat/archive/2008/03/13/linq-framework-design-guidelines.aspx

But yeah, the last type here in the Func<> is what it returns. (However, I can still recommend using the Lambda expression, as it's pretty clean, neat and serves the Func<> best.

(Also, look at what intellisence gives you when you write "new Func<....", it should give you a good idea of what Func wants and can do!)

Hope I was of help.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号