.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan
Post New Web Links

Implicit-type lambda expression: is it possible?

Posted By:      Posted Date: August 28, 2010    Points: 0   Category :.NET Framework
 
Hi all, i was plaing around with LINQ and lambda expressions. I was trying to find duplicated files in my system. After a while a realized that duplicated could mean: - same name - same size and extension - ....   So i wrote this code: DirectoryInfo rootDirectory = ....; var groupFiles = selector => rootDirectory.EnumerateFiles("*", SearchOption.AllDirectories).GroupBy(selector).Select(g => new { g.Key, Info = g, Count = g.Count() }).Where(g => g.Count > 1); var groupsByName = groupFiles(f => f.Name); var groupsBySize = groupFiles(f => new { f.Length, f.Extension}); But i get the following error: Error 1 Cannot assign lambda expression to an implicitly-typed local variable So i tryed to make the type explicit and i realized that is not so easy. So what i'm missing?! IMPORTANT. 'm not tying to have the code working. I can solve the issue by duplicating code (even if i hate to do that) I'm rtying to improve my skills with LINQ and Lambda Expressions. Thanks all!!  


View Complete Post


More Related Resource Links

Arithmetic overflow error converting expression to data type smallint

  
Can anyone tell me what exactly this means? Arithmetic overflow error converting expression to data type smallint. 

Data type mismatch in criteria expression.

  
Protected Sub btnSave_OnClick(ByVal sender As Object, ByVal e As EventArgs) Dim StartDateYear As Integer = Int32.Parse(2000 + tbStartDateYear.Text) Dim StartDateMonth As Integer = Int32.Parse(ddlStartDateMonth.SelectedValue) Dim StartDateDay As Integer = Int32.Parse(ddlStartDateDay.SelectedValue) Dim startDate As Date = New Date(StartDateYear, StartDateMonth, StartDateDay) Dim folderStartDate As String = Convert.ToDateTime(startDate).ToString("dd.mm.yyyy") Dim projectName As String = tbProjectName.Text Dim projectCategory As String = ddlProjectCategory.Text Dim projectID As String = "" Dim objConnection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|MOPPS.mdb;") Dim insertSQL As String = "INSERT INTO Projects([Project Title], [Start Date], [Project category]) VALUES (@projectName, @startDate, @projectCategory);" Dim insertCommand As New OleDbCommand(insertSQL, objConnection) Dim IDSQL As String = "SELECT [ProjectID] FROM Projects WHERE [Project Title]='" & projectName & "' AND [Start Date]='" & startDate & "' AND [Project category]='" & projectCategory & "';" Dim IDCommand As New OleDbCommand(IDSQL, objConnecti

A new expression requires (), [] or {} after type ??

  
Hello - I am fairly new to C# and I am having trouble with a line of code highlighted below. I get a
error: "A new expression requires (), [] or {} after type" Can someone help? Thanks
 
 
namespace BackgrountPrint
{
 class Program
    {

       public BackgroundPrint.ReportService.ReportingService rs;
        public BackgroundPrint.ReportExecution2005.ReportExecutionService   rsExec;
        


        static void Main(string[] args)
        {


           ReportService.ReportingService rs = new BackgroundPrint.ReportService.ReportingService

  
           rs.Credentials = CredentialCache.DefaultCredentials ;
      



        }


 }


RenderAction with Lambda Expression in MVC 3.0 preview 1

  

Hi all, i have the following, which works:

@{Html.RenderAction("Detail", "Help", new { pageName = "press" });}

But instead i'd like to use a lambda expression to get away from the string bits. I tried using the following (which is the nearest approximation i could figure based on my limited knowledge of the engine):

@{Html.RenderAction<HelpController>(x => x.Detail("press"));}

But i get the following error:

The non-generic method 'System.Web.Mvc.Html.ChildActionExtensions.RenderAction(System.Web.Mvc.HtmlHelper, string, string, System.Web.Routing.RouteValueDictionary)' cannot be used with type arguments

However, i'm reading in the Apress MVC 2.0 book that it is in fact declared as a method that takes type arguments. Am i missing an assembly reference, or has it not been included in the MVC 3.0 Preview 1 build?


An expression of non-boolean type specified in context where a condition is expected, near ','.

  

An expression of non-boolean type specified in context where a condition is expected, near ','.

SELECT Code, Name
FROM DimCounty c
WHERE PublicationId = 44
and ((c.Name = @CountySelection) OR 
((c.Code BETWEEN '001' AND '102') AND
((@CountySelection) = 'ACTUAL')) OR
((@CountySelection) = 'ALL'))
I am gettting an 'An expression of non-boolean type specified in context where a condition is expected, near ','.' when I try to run this query in reporting services.

SSIS 2008-Variable Expression Type Cast Syntax Error

  

Hi all members.

I need to ask for the following code. I need to convert the variable into a string.

"Select Distinct convert (int ,A.CustomerCategory) as AccountReceivableCategoryID, convert (varchar(40), B.Text) as AccountReceivableCategoryNameE
from Inkunde A , inpara B
where A.CustomerCategory= B.SearchItem
and B.Language1 = 'EN'
and B.ParameterName = 'CATEGORY'
and A.CustomerCategory = (DT_STR,200,1252) "+  @[User::CategoryID] +"
Order By A.CustomerCategory"

Kindly any member let me know, How to correctly use the Type Cast fucntion in variables

Thanks and Best Regards,

Izhar


Data type mismatch in criteria expression: date

  

 

I am getting a "Data type mismatch in criteria expression" error when trying the following SELECT statement.

strdt and spdate are Date types in my vb codebehind and the Contract field name is a DateTime field.

thanks for your help

 

Dim

nmxSQL As String = "SELECT * FROM Nymex WHERE (NymexID='" & nymID & "' And Contract>='" & strdt & "' And Contract<='" & spdate & "')"


Localizing implicit type validation messages

  

I'm having trouble with the implicit type validation for model properties. The validation/error messages (for numeric fields explicitly) are printed in English (I want them to be printed in Swedish). Does anyone know how to override those messages? Or can I turn of implicit type validation?

The error message I'd like to translate/localize is "The field {0} must be a number."


Help tloading a dropdownlist using lambda expression??? o/

  

Hello everyone


Thank you for your time..


I´m trying to load one field from the table using Lambda


 public void Search()

        {

            ddlcity.DataSource = companiesBLL.Find(e => e.city.Equals(e.ID_COMPANY)).ToList();

            ddlcity.DataBind();

        }


ddlcity = dropdown

id_city = main Id (primarykey of that table)


but i want to only load the city field from the table Company.


I´d appreciate if anyone could help me.


=)

 public void Bairro()
        {
            ddlBairro.DataSource = empresasBLL.Find(e => e.BAIRRO.Equals(e.ID_EMPRESA)).ToList();

Implicit conversion from data type sql_variant to varbinary is not allowed

  

Here are my codes:

string strToday = DateTime.Today.ToShortDateString();
string strTime = DateTime.Now.ToShortTimeString();
DateTime dtmDate = Convert.ToDateTime(strToday + " " + strTime);

e.Values["insertDate"] = dtmDate;
e.Values["modDate"] = dtmDate;


And here's the error I got:


Implicit conversion from data type sql_variant to varbinary is not allowed. Use the CONVERT function to run this query.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Implicit conversion from data type sql_variant to varbinary is not allowed. Use the CONVERT function to run this query.


Lambda expression

  

Hi guys,

Anybody please give me the example How to use Lambda expression in linq.please give a simple example and describe it also.

Thank's


How to create a generic Lambda Expression

  

I Use entity framework 4.

Here is my model

Language
LangID
LangName


Product
PrdID
IsActive


ProductText
PrdID
LangID
Text


Category
CatID
IsActive


CategoryText
CatID
LangID
Text

Each time I want the text for one of these model, I execute this lambda expression p=> p.LangID == 1

Is it possible to create a generic lambda expression function that all of these model can use.?


How to use lambda expression to replace if-else

  

I have a list of possible nodes as a child of parent node, i need to compare the nodeName and if node name matches, i need to get the value and assign it to member variable.

public class Contacts
{
private string FirstName;
private string LastName;
  public LoadContacts(XmlNode contactNode)
  {
    string[] names={
     FirstName,
     LastName,
     PhoneNumber,
     Address
    }
    foreach(XmlNode child in contactNode)
   {
     
     if( child.Name == names[0])
       m_firstName = child.Value;
     else
     if(child.Name == names[1])
       m_lastName = child.Value;
     else...
 
    }
 }

Is there a way of re-factor the same code with Lambda expression.

Thanks in Advance.


C--s

Arithmetic overflow error converting expression to data type int.

  

I have a table with a row called row1, this row1 is a bigint and has values from 0  To  4278190080

 

I am running a query such as: select top 1 * from tableA where row1 <= (((73*256+62)*256+53)*256 + 12)

 

How can I get this to work? I tried to do where cast(row1 as float) <= ....... but I get the same error.



DRY with Lambda Expression (errors management)

  

In my current project, I have made a miracle with Lambda Expression. Have you ever implemented something like this:

    public abstract class GenericRepository<TEntity> : IRepository<TEntity> where TEntity : classIEntity
    {
        private readonly ILog _logger;

        protected GenericRepository()
            : this(IoC.GetInstance<IUnitOfWork>(), IoC.GetInstance<ILog>()
 &nb

ExpressionTextBox expression type

  

Hi

I'm developing Serialize and Deserialize activities (binary serialization).

I need to validate that evaluated expression  type (in design time) is annotated with SerializableAttribute.

I haven't found property for that  but ExpressionType  - which is ExpressionTextBox  expected type (in my case I set it to "object")

How this could be achivied ?

Thanks


How do I require a multiple of a type of expression (e.g. 2 uppers, 2 lowers, etc.) for password com

  

I read the pinned post on this forum for password complexity and tried to adapt it to my needs but can't seem to force the requirement of no length, 2 upper, 2 lower, 2 specials, and 2 numbers in the regex:

Started with from the forum post:  

^(?!.{31})(?=.{8})(?=.*[^A-Za-z])(?=.*[A-Z])(?=.*[a-z]).*$

And tried:

^(?=.*[^A-Za-z])(?=.*[A-Z])(?=.*[a-z]).*$
^(?=.*[^A-Za-z0-9])(?=.*[^A-Za-z0-9])(?=.*[0-9])(?=.*[0-9])(?=.*[A-Z])(?=.*[A-Z])(?=.*[a-z])(?=.*[a-z]).*$

...but can't seem to get it to work.  As you can see, I've just duplicated the expression I'm trying to use to match the different categories twice to try and get the desired affect of enforcing a 2x match.  The pattern should match things like:

12qw!@QW
1q!Q2w@W
1234qwer!@#$QWER
1q!Q2w@W3e#E4r$R

Thanks in advance.


Categories: 
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend