SQLCE数据库的几点研究
一.linq中的distinct
该知识参考自这里
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class FastPropertyComparer<T> : IEqualityComparer<T> { private Func<T, Object> getPropertyValueFunc = null; /// <summary> /// 通过propertyName 获取PropertyInfo对象 /// </summary> /// <param name="propertyName"></param> public FastPropertyComparer(string propertyName) { PropertyInfo _PropertyInfo = typeof(T).GetProperty(propertyName, BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public); if (_PropertyInfo == null) { throw new ArgumentException(string.Format("{0} is not a property of type {1}.", propertyName, typeof(T))); } ParameterExpression expPara = Expression.Parameter(typeof(T), "obj"); MemberExpression me = Expression.Property(expPara, _PropertyInfo); getPropertyValueFunc = Expression.Lambda<Func<T, object>>(me, expPara).Compile(); } #region IEqualityComparer<T> Members public bool Equals(T x, T y) { object xValue = getPropertyValueFunc(x); object yValue = getPropertyValueFunc(y); if (xValue == null) return yValue == null; return xValue.Equals(yValue); } public int GetHashCode(T obj) { object propertyValue = getPropertyValueFunc(obj); if (propertyValue == null) return 0; else return propertyValue.GetHashCode(); } #endregion }
备注:这样可以把数据库里重复的数据去掉(并非只是查询出来)。distinct()方法有2个作用,1个是用哈希进行查找,另一个是进行删除。
二.清除数据库缓存:
①删除15天前的信息(利用时间戳判断)。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using (var db = new MyDataContext()) { if (db.DatabaseExists()) { var mystamp = long.Parse(GetTimeStamp(DateTime.Now.AddDays(-15))); IQueryable<MyContent> contentdb = from s in db.MyContents where s.stamp < mystamp select s; db.MyContents.DeleteAllOnSubmit(contentdb); db.SubmitChanges(); } }
时间戳和本地时间转换参考这里
优点:控制灵活。
缺点:删除效率低。
②直接删除数据库,然后重新建。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using (IsolatedStorageFile.GetUserStoreForApplication()) if (IsolatedStorageFile.GetUserStoreForApplication().FileExists("MyDb.sdf")) IsolatedStorageFile.GetUserStoreForApplication().DeleteFile("MyDb.sdf"); using (var db = new MyDataContext()) { switch (db.DatabaseExists()) { case false: db.CreateDatabase(); Debug.WriteLine(DateTime.Now.ToLongTimeString() + "数据库创建完成"); break; default: Debug.WriteLine("数据库已经存在"); break; } } PublicMethod.Showtoast("清理成功~");
优点:删除效率高。
缺点:控制不灵活。
备注:winphone是流畅的系统,看个人需求选择吧。
三.删除操作:
observablecollection是个极好的类,能动态更新数据和UI,适用于删除操作。
用法参考这里。
备注:observable的好处是,不用重复的,当从网络上获取好数据后赋值,只需要在程序开头赋值,
就会有相应接口自动监听,提高效率。
四.linq拓展方法any和count性能区别:
判断有没有元素,莫用count,用any比较好,因为一旦有,any立即返回true,count要遍历完。