Search

just show me the code

Showing posts with label linq. Show all posts
Showing posts with label linq. Show all posts

Wednesday, May 13, 2009

Linq Filter by adding Where Clause


  187         public IQueryable<Talent> GetTalents(string searchExpression)
  188         {
  189             IQueryable<Talent> t;
  190             if (string.IsNullOrEmpty(searchExpression))
  191             {
  192                 t = _repository.GetTalents();
  193             } 
  194             else
  195             {
  196                 t = BasicSearch(searchExpression);
  197             }
  198             return t;
  199         }
  200
  201         private static readonly char[] SplitDelimiters = " ".ToCharArray();
  202
  203         // search should come in as  'jon johnny323@yahoo.com rodgers'
  204         private IQueryable<Talent> BasicSearch(string search)
  205         {
  206             // Just replacing "  " with " " wouldn't help with "a      b"
  207             string[] terms = search.Trim()
  208                                    .ToLower()
  209                                    .Split(SplitDelimiters,
  210                                           StringSplitOptions.RemoveEmptyEntries);
  211             IQueryable<Talent> talents = _repository.GetTalents();
  212             foreach (string s in terms)
  213             {
  214                 talents = AddBasicSearch(talents, s);
  215             }
  216             return talents;
  217         }
  218
  219         private IQueryable<Talent> AddBasicSearch(IQueryable<Talent> t, string s)
  220         {
  221             return t.Where(x =>  x.FirstName.ToLower().Contains(s)
  222                     || x.LastName.ToLower().Contains(s) 
  223                     || x.Email.ToLower().Contains(s) 
  224                     || x.LanguagesString.ToLower().Contains(s) 
  225                     );
  226         }

Wednesday, December 10, 2008

Linq to Lambda

I changed a Linq expression to a Lambda expression so I could refactor the filter. Here is the before and after

Before: (Linq expression)
results = from u in ctx.ActiveUsers
          where (u.CompanyID != 1 &&
                   (u.LastName.ToLower().Contains(searchString)
                   || u.Email.ToLower().Contains(searchString)
                   || u.Company.Name.ToLower().Contains(searchString)))
          orderby u.LastName, u.FirstName
          select new Employee
          {
              ID = u.ID,
              FirstName = u.FirstName,
              LastName = u.LastName,
              Email = u.Email,
              CompanyName = u.Company.Name,
              CompanyID = u.CompanyID.ToString()
          };


After: (Lambda expression)
results = ctx.ActiveUsers
    .Where(Employee.GetExpression(searchString))
    .OrderBy(u =>  u.LastName ).ThenBy(u => u.FirstName)
    .Select(u => new Employee {
ID = u.ID
      , FirstName = u.FirstName
, LastName = u.LastName
      , Email = u.Email
, CompanyName = u.Company.Name
      , CompanyID = u.CompanyID.ToString() });


plus this to keep the where expression the same on the count:
private static Expression<Func<User, bool>> GetExpression(string searchString)
{ 
    Expression<Func<User, bool>> p = (u => u.CompanyID != 1 &&
                       (u.LastName.ToLower().Contains(searchString)
                       || u.Email.ToLower().Contains(searchString)
                       || u.Company.Name.ToLower().Contains(searchString)));
    return p;
}

so that GetExpression can be used here to make sure that our count query is the same as the select
public static int GetCustomerCount()
{
    UserContext ctx = new UserContext();
    int totalRecords;
 
    string searchString = SearchString; 
 
    totalRecords = ctx.ActiveUsers.Count(Employee.GetExpression(searchString));
    return totalRecords;
}




Monday, December 8, 2008

Linqpad


Linqpad is a nice way to learn how to write linq statements. There is no install required. Check it out here. Thanks Joseph

Wednesday, November 5, 2008

asp.net handlers serving xml

your handler code
namespace XXXX.TourAdmin.Web.Admin
{
    /// 
    /// Summary description for $codebehindclassname$
    /// 
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class VideoHandler : IHttpHandler
    {
 
        public void ProcessRequest(HttpContext context)
        {
            //context.Response.ContentType = "text/plain";
            context.Response.ContentType = "UTF-8";
            context.Response.Write(this.GetVideoXml());
        }
 
        protected string GetVideoXml()
        {
            VideoContext vc = new VideoContext();
            var videos = from v in vc.Videos
                         select new 
                         {
                             VideoClip = v.FileLocation,
                             Title = v.Title,
                             Date = v.VideoDate,
 
                         };
 
            XDocument xmlDoc = new XDocument();
            XElement xEleVideos = new XElement("videos");
            xmlDoc.Add(xEleVideos); 
            foreach (var v in videos)
            {
                xEleVideos.Add(new XElement("video",  new XAttribute("VideoClip", v.VideoClip),
                    new XAttribute("Title", v.Title), new XAttribute("Copy", v.Date)));
            }
            string s = xmlDoc.ToString();
            return s;
        }
 
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
here is the data:



TitleFileLocationVideoDateactive
Miami, Florida200809142009-02-12 00:00:001

now put the url in the address bar
http://localhost/XXXX.TourAdmin.Web/Admin/VideoHandler.ashx
<videos>
  <video VideoClip="20080914" Title="Miami, Florida" copy="2009-02-12T00:00:00" />
<videos>
Props to Lewis

Tuesday, November 4, 2008

Linq to xml

Linq (Language Integrated Query) works on xml too

<content>
  <gallery Name="All Videos">
    <video VideoClip="20081014.flv" Title="Orlando, Florida" Copy="Feb 12, 2009"/>
    <video VideoClip="20081121.flv" Title="Atlanta, Georgia" Copy="Feb 12, 2009"/>
  </gallery>
</content>



protected void LoadGallaryList()
{
    string xmlFile = this.Server.MapPath("~/Flash/_xml/video.xml"); 
    XDocument xmlDoc = XDocument.Load(xmlFile); 
    var videos = from v in xmlDoc.Descendants("video") // .Elements("video")
                 select new 
                 {
                     VideoClip = v.Attribute("VideoClip").Value,
                     Title = v.Attribute("Title").Value,
                     Date = v.Attribute("Copy").Value,
                 }; 
    foreach (var v in videos)
    {
        lblCurrent.Text += "title:" + v.Title + " VideoClip:" + v.VideoClip + " Date:" + v.Date + "<br/>";
    }
}

output:
title:Orlando, Florida VideoClip:20080914.flv Date:Feb 12, 2009
title:Atlanta, Georgia VideoClip:20081121.flv Date:Feb 12, 2009

Contributors