开发者

Linq: How to find rows searching in two columns with the same criteria

开发者 https://www.devze.com 2022-12-14 11:12 出处:网络
In my controller, I\'ve this action method called \"SearchForContact,\" which takes 2 strings parameters firstName and LastName. There are 开发者_开发问答3 situations:

In my controller, I've this action method called "SearchForContact," which takes 2 strings parameters firstName and LastName. There are 开发者_开发问答3 situations:

  • If both parameters are null, the view is redisplayed with an error message, prompting the user to enter at least one of the 2 parameters

  • if both parameters are not null, I can retrieve contacts and display the result on the view

  • Unfortunately, when either of the parameters is null, I get nothing. I suspect that I did not write correctly my Linq Statements.

here's the statement that process the search:

var contacts = contactRepository.SearchForContacts(firstName, lastName).ToList();

Here are my helper methods located in my repository class (ContactRepository.cs) located in the models folder.

public IQueryable<Contact> SearchForContacts(string firstName, string lastName)
    {
        if (firstName == null)
            return OneCriteria(lastName);
        if (nom == null)
            return OneCriteria(firstName);
        else
            return TwoCriteria(firstName, lastName);

    }
    private IQueryable<Contact> OneCriteria(string criteria)
    {
        var contacts = from contact in db.Contacts
                       where ((contact. firstName == criteria) ||
                              (contact. lastName == criteria))
                       orderby contact. firstName
                       select contact;
        return contacts;
    }
    private IQueryable<Contact> TwoCriteria(string firstName, string lastName)
    {
        var contacts = from contact in db.Contacts
                       where ((contact. firstName == firstName) &&
                             (contact. lastName == lastName))
                       orderby contact. firstName
                       select contact;
        return contacts;
    }

Thanks for helping


Should you not change

if (nom == null)

to

if (lastName== null)

Seems to work fine when i tested it.


try this

 if ((firstName == null) && (lastName != null)  )
        return OneCriteria(lastName);

if ((firstName != null) && (lastName == null) ) return OneCriteria(firstName);

else return TwoCriteria(firstName, lastName);

hope this helps.


You can try the following: if(firstName == null && lastname == null) {do your error}

else {

var contacts = from contact in db.Contacts select contact;

if(firstName != null) contacts = from FN in contacts where (FN.firstName == firstName) select FN;

if(lastName != null) contacts = from LN in contacts where (FN.lastName == lastName) select LN;

}

0

精彩评论

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