开发者

how to convert multiple linq statement to selectmany

开发者 https://www.devze.com 2022-12-08 02:56 出处:网络
I am a beginner with LINQ and lambda function\'s. I was wondering how can i convert multiple linq statement to one statement using selectmany function.

I am a beginner with LINQ and lambda function's. I was wondering how can i convert multiple linq statement to one statement using selectmany function.

string viewname = (from a in StoredProcedureParameters.Tables[0].AsEnumerable()
                 where a.Field<string>("ViewName") == displayName
                 s开发者_C百科elect a.Field<string>("View")).Single();

DateTime date = (from d in StoredProcedureParameters.Tables[0].AsEnumerable()
                select d.Field<DateTime>("Date")).First();

Thanks for help in advance.


If you want a single query, you could have the select value be an anonymous type. But the scope of the return value is the method where the type is created.

var result = (from a in StoredProcedureParameters.Tables[0].AsEnumerable()
                 where a.Field<string>("ViewName") == displayName
                 select new { View = a.Field<string>("View"),
                              Date = d.Field<DateTime>("Date") }).Single();

then the variable result will be an object with the properties 'View' and 'Date'. You can't return this value from a method though. If you need to return the value, you could create a simple class

public class ViewDate
{
  public string View { get; set; }
  public DateTime Date { get; set; }
}

Then using an object initializer, you will end up with result containing an instance of the ViewDate object, which you can return from your method.

var result = (from a in StoredProcedureParameters.Tables[0].AsEnumerable()
                 where a.Field<string>("ViewName") == displayName
                 select new ViewDate() { View = a.Field<string>("View"),
                              Date = d.Field<DateTime>("Date") }).Single();


I don't think SelectMany does what you think it does. It's usually just a flatten operation. Why do you think it would help you in this case? Why do you want to avoid two queries?

0

精彩评论

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