博客 (9)

语言集成查询(LINQ)为 C# 和 VB 提供语言级查询功能和高阶函数 API,让你能够编写具有很高表达力度的声明性代码。

LINQ 有两种写法:查询语法和方法语法,查询语法又称查询表达式语法。

查询语法:

from 变量名 in 集合 where 条件 select 结果变量

方法语法:

集合.Where(变量名 => 条件)


LINQ 的标准查询运算符及语法示例

类型操作符功能方法语法查询语法
投影操作符Select用于从集合中选择指定的属性或转换元素
cats.Select(cat => cat.color)
from cat in cats
select cat.color
SelectMany用于在嵌套集合中选择并平铺元素
families.SelectMany(family => family.members
.Select(member => member.name))
from family in families
from member in family.members
select member.name
限制操作符Where根据指定的条件筛选集合中的元素
cats.Where(cat => cat.color == "white")
from cat in cats
where cat.color == "white"
select cat
排序操作符

OrderByOrderByDescending、ThenBy、ThenByDescending

用于对集合中的元素进行排序
cats.OrderBy(cat => cat.age)
from cat in cats
order by cat.age
select cat
Reverse将集合中的元素顺序反转
cats.Reverse()


联接操作符

Join

GroupJoin

用于在两个集合之间执行内连接(Join)操作,或者对一个集合进行分组连接(GroupJoin)操作内联接
families.Join(
    members,
    family => family.familyId,
    member => member.familyId,
    (family, member) => new
    {
        family.familyId,
        member.name,
    })

左连接

families.GroupJoin(
    members,
    family => family.familyId,
    member => member.familyId,
    (family, familyMembers) => new
    {
        family.familyId,
        name = familyMembers.FirstOrDefault()?.name
    })


内联接
from family in families
join member in members on family.familyId equals member.familyId
select new
{
    family.familyId,
    member.name,
}

左连接

from family in families
join member in members on family.familyId equals member.familyId into g
from member in g.DefaultIfEmpty()
select new
{
    family.familyId,
    name = member?.name,
}


分组操作符GroupBy根据指定的键对集合中的元素进行分组

串联操作符Concat将两个集合连接成一个新集合

聚合操作符

AggregateAverage、Count、LongCount、Max、Min、Sum

Aggregate 可以用于在集合上执行自定义的累积函数,其他方法用于计算集合中的元素的平均值、总数、最大值、最小值和总和

集合操作符

DistinctUnion、Intersect、Except

用于执行集合间的不同操作,Distinct 移除重复元素,Union 计算两个集合的并集,Intersect 计算两个集合的交集,Except 计算一个集合相对于另一个集合的差集

生成操作符

EmptyRange、Repeat

Empty 创建一个空集合,Range 创建一个包含一系列连续数字的集合,Repeat 创建一个重复多次相同元素的集合

转换操作符

AsEnumerableCast、OfType、ToArray、ToDictionary、ToList、ToLookup

这些方法用于将集合转换为不同类型的集合或字典

元素操作符

DefaultIfEmptyElementAtElementAtOrDefaultFirst、Last、FirstOrDefault、LastOrDefault、Single、SingleOrDefault

这些方法用于获取集合中的元素,处理可能的空集合或超出索引的情况

相等操作符SequenceEqual用于比较两个集合是否包含相同的元素,顺序也需要相同

量词操作符All、Any、Contains用于检查集合中的元素是否满足特定条件,All 检查是否所有元素都满足条件,Any 检查是否有任何元素满足条件,Contains 检查集合是否包含特定元素

分割操作符Skip、SkipWhile、Take、TakeWhile用于从集合中跳过一些元素或只取一部分元素,可以结合特定条件进行操作

了解立即执行延迟执行可以大大改善性能。

xoyozo 9 个月前
854
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace xxx.xxx.xxx.Controllers
{
    public class DiscuzTinyintViewerController : Controller
    {
        public IActionResult Index()
        {
            using var context = new Data.xxx.xxxContext();

            var conn = context.Database.GetDbConnection();
            conn.Open();
            using var cmd = conn.CreateCommand();
            cmd.CommandText = "SELECT `TABLE_NAME` FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE();";
            Dictionary<string, List<FieldType>?> tables = new();

            using var r = cmd.ExecuteReader();
            while (r.Read())
            {
                tables.Add((string)r["TABLE_NAME"], null);
            }
            conn.Close();

            foreach (var table in tables)
            {
                var conn2 = context.Database.GetDbConnection();
                conn2.Open();
                using var cmd2 = conn2.CreateCommand();
                cmd2.CommandText = "DESCRIBE " + table.Key;
                using var r2 = cmd2.ExecuteReader();
                List<FieldType> fields = new();
                while (r2.Read())
                {
                    if (((string)r2[1]).Contains("tinyint(1)"))
                    {
                        fields.Add(new()
                        {
                            Field = (string)r2[0],
                            Type = (string)r2[1],
                            Null = (string)r2[2],
                        });
                    }
                }
                conn2.Close();
                tables[table.Key] = fields;
            }

            foreach (var table in tables)
            {
                foreach (var f in table.Value)
                {
                    var conn3 = context.Database.GetDbConnection();
                    conn3.Open();
                    using var cmd3 = conn3.CreateCommand();
                    cmd3.CommandText = $"SELECT {f.Field} as F, COUNT({f.Field}) as C FROM {table.Key} GROUP BY {f.Field}";
                    using var r3 = cmd3.ExecuteReader();
                    List<FieldType.ValueCount> vs = new();
                    while (r3.Read())
                    {
                        vs.Add(new() { Value = Convert.ToString(r3["F"]), Count = Convert.ToInt32(r3["C"]) });
                    }
                    conn3.Close();
                    f.groupedValuesCount = vs;
                }
            }

            return Json(tables.Where(c => c.Value != null && c.Value.Count > 0));
        }

        private class FieldType
        {
            public string Field { get; set; }
            public string Type { get; set; }
            public string Null { get; set; }
            public List<ValueCount> groupedValuesCount { get; set; }
            public class ValueCount
            {
                public string Value { get; set; }
                public int Count { get; set; }
            }
            public string RecommendedType
            {
                get
                {
                    if (groupedValuesCount == null || groupedValuesCount.Count < 2)
                    {
                        return "无建议";
                    }
                    else if (groupedValuesCount.Count == 2 && groupedValuesCount.Any(c => c.Value == "0") && groupedValuesCount.Any(c => c.Value == "1"))
                    {
                        return "bool" + (Null == "YES" ? "?" : "");
                    }
                    else
                    {
                        return "sbyte" + (Null == "YES" ? "?" : "");
                    }
                }
            }
        }
    }
}
[{
	"key": "pre_forum_post",
	"value": [{
		"field": "first",
		"type": "tinyint(1)",
		"null": "NO",
		"groupedValuesCount": [{
			"value": "0",
			"count": 1395501
		}, {
			"value": "1",
			"count": 179216
		}],
		"recommendedType": "bool"
	}, {
		"field": "invisible",
		"type": "tinyint(1)",
		"null": "NO",
		"groupedValuesCount": [{
			"value": "-5",
			"count": 9457
		}, {
			"value": "-3",
			"count": 1412
		}, {
			"value": "-2",
			"count": 1122
		}, {
			"value": "-1",
			"count": 402415
		}, {
			"value": "0",
			"count": 1160308
		}, {
			"value": "1",
			"count": 3
		}],
		"recommendedType": "sbyte"
	}, {
		"field": "anonymous",
		"type": "tinyint(1)",
		"null": "NO",
		"groupedValuesCount": [{
			"value": "0",
			"count": 1574690
		}, {
			"value": "1",
			"count": 27
		}],
		"recommendedType": "bool"
	}, {
		"field": "usesig",
		"type": "tinyint(1)",
		"null": "NO",
		"groupedValuesCount": [{
			"value": "0",
			"count": 162487
		}, {
			"value": "1",
			"count": 1412230
		}],
		"recommendedType": "bool"
	}, {
		"field": "htmlon",
		"type": "tinyint(1)",
		"null": "NO",
		"groupedValuesCount": [{
			"value": "0",
			"count": 1574622
		}, {
			"value": "1",
			"count": 95
		}],
		"recommendedType": "bool"
	}, {
		"field": "bbcodeoff",
		"type": "tinyint(1)",
		"null": "NO",
		"groupedValuesCount": [{
			"value": "-1",
			"count": 935448
		}, {
			"value": "0",
			"count": 639229
		}, {
			"value": "1",
			"count": 40
		}],
		"recommendedType": "sbyte"
	}, {
		"field": "smileyoff",
		"type": "tinyint(1)",
		"null": "NO",
		"groupedValuesCount": [{
			"value": "-1",
			"count": 1359482
		}, {
			"value": "0",
			"count": 215186
		}, {
			"value": "1",
			"count": 49
		}],
		"recommendedType": "sbyte"
	}, {
		"field": "parseurloff",
		"type": "tinyint(1)",
		"null": "NO",
		"groupedValuesCount": [{
			"value": "0",
			"count": 1572844
		}, {
			"value": "1",
			"count": 1873
		}],
		"recommendedType": "bool"
	}, {
		"field": "attachment",
		"type": "tinyint(1)",
		"null": "NO",
		"groupedValuesCount": [{
			"value": "0",
			"count": 1535635
		}, {
			"value": "1",
			"count": 2485
		}, {
			"value": "2",
			"count": 36597
		}],
		"recommendedType": "sbyte"
	}, {
		"field": "comment",
		"type": "tinyint(1)",
		"null": "NO",
		"groupedValuesCount": [{
			"value": "0",
			"count": 1569146
		}, {
			"value": "1",
			"count": 5571
		}],
		"recommendedType": "bool"
	}]
}]


xoyozo 2 年前
1,459

测试在长度为 403 的字符串中查找,特意匹配最后几个字符:

string a = "";
for (int i = 0; i < 100; i++) { a += "aBcD"; }
a += "xYz";
string b = "xyz"; // 特意匹配最后几个字符

Stopwatch sw1 = Stopwatch.StartNew();
bool? r1 = null; 
for (int i = 0; i < 10000; i++) { r1 = a.IndexOf(b) >= 0; }
sw1.Stop();

Stopwatch sw2 = Stopwatch.StartNew();
bool? r2 = null; 
for (int i = 0; i < 10000; i++) { r2 = a.Contains(b); }
sw2.Stop();

Stopwatch sw3 = Stopwatch.StartNew();
bool? r3 = null; 
for (int i = 0; i < 10000; i++) { r3 = a.ToUpper().Contains(b.ToUpper()); }
sw3.Stop();

Stopwatch sw4 = Stopwatch.StartNew();
bool? r4 = null; 
for (int i = 0; i < 10000; i++) { r4 = a.ToLower().Contains(b.ToLower()); }
sw4.Stop();

Stopwatch sw5 = Stopwatch.StartNew();
bool? r5 = null; 
for (int i = 0; i < 10000; i++) { r5 = a.Contains(b, StringComparison.OrdinalIgnoreCase); }
sw5.Stop();

Stopwatch sw6 = Stopwatch.StartNew();
bool? r6 = null; 
for (int i = 0; i < 10000; i++) { r6 = a.Contains(b, StringComparison.CurrentCultureIgnoreCase); }
sw6.Stop();

Stopwatch sw7 = Stopwatch.StartNew();
bool? r7 = null; 
for (int i = 0; i < 10000; i++) { r7 = Regex.IsMatch(a, b); }
sw7.Stop();

Stopwatch sw8 = Stopwatch.StartNew();
bool? r8 = null; 
for (int i = 0; i < 10000; i++) { r8 = Regex.IsMatch(a, b, RegexOptions.IgnoreCase); }
sw8.Stop();

return Json(new
{
    IndexOf_________________ = sw1.Elapsed + " " + r1,
    Contains________________ = sw2.Elapsed + " " + r2,
    ToUpper_________________ = sw3.Elapsed + " " + r3,
    ToLower_________________ = sw4.Elapsed + " " + r4,
    OrdinalIgnoreCase_______ = sw5.Elapsed + " " + r5,
    CurrentCultureIgnoreCase = sw6.Elapsed + " " + r6,
    IsMatch_________________ = sw7.Elapsed + " " + r7,
    IsMatchIgnoreCase_______ = sw8.Elapsed + " " + r8,
});

结果参考:

{
"indexOf_________________": "00:00:00.1455812 False",
"contains________________": "00:00:00.0003791 False",
"toUpper_________________": "00:00:00.0038182 True",
"toLower_________________": "00:00:00.0026113 True",
"ordinalIgnoreCase_______": "00:00:00.0096550 True",
"currentCultureIgnoreCase": "00:00:00.1596517 True",
"isMatch_________________": "00:00:00.0053627 False",
"isMatchIgnoreCase_______": "00:00:00.0084132 True"
}


xoyozo 2 年前
1,314

这个现象在国产浏览器上使用极速内核时出现,原因是百度编辑器上传图片功能通过 <form /> 提交到 <iframe /> 时,因跨域导致 cookie 丢失。

ASP.NET 的 ASP.NET_SessionId 默认的 SameSite 属性值为 Lax,将其设置为 None 即可:

protected void Session_Start(object sender, EventArgs e)
{
    // 解决在部分国产浏览器上使用百度编辑器上传图片时(iframe),未通过 cookie 传递 ASP.NET_SessionId 的问题
    string ua = Request.UserAgent ?? "";
    var browsers = new string[] { "QQBrowser/" /*, "Chrome/" 不要直接设置 Chrome,真正的 Chrome 会出现正常页面不传递 Cookie 的情况 */ };
    bool inWeixin = ua.Contains("MicroMessenger/"); // 是否在微信中打开(因微信PC端使用QQ浏览器内核,下面的设置会导致其网页授权失败)
    if (browsers.Any(c => ua.Contains(c)) && !inWeixin)
    {
        Response.Cookies["ASP.NET_SessionId"].SameSite = SameSiteMode.None;
    }
}

以上代码加入到 Global.asaxSession_Start 方法中,或百度编辑器所在页面。

注意一:SameSite=None 时会将父页面的 cookie 带入到 iframe 子页的请求中,从而导致 cookie 泄露,请确保项目中无任何站外引用,如网站浏量统计器、JS组件远程CDN等!

注意二:微信PC版的内嵌浏览器使用QQ浏览器内核,以上代码会导致其微信网页授权不能正常执行。

xoyozo 4 年前
3,437

* 若无特殊注明,本文中的“手机”包含平板电脑


判断网页是否在移动设备中打开


Web Form:

public static bool IsMobileDevice
{
    get
    {
        return (HttpContext.Current.Request.Browser?.IsMobileDevice ?? false)
            || (HttpContext.Current.Request.UserAgent?.Contains("Mobile") ?? false);
    }
}


ASP.NET Core:

好像还没有找到,可能是因为随着响应式布局的流行以及电脑和手机之间的界线越来越不明朗,取消了这个判断?


判断网页是否在微信浏览器中打开(宽松)


Web Form:

public bool IsInWechat
{
    get
    {
        return HttpContext.Current.Request.UserAgent?.Contains("MicroMessenger") ?? false;
    }
}


ASP.NET Core:

需注入 IHttpContextAccessor

public bool IsInWechat
{
    get
    {
        string ua = httpContextAccessor.HttpContext.Request.Headers[HeaderNames.UserAgent];
        return ua?.Contains("MicroMessenger") ?? false;
    }
}


判断网页是否在微信浏览器中打开(严谨)


使用 JS-SDK 网页授权来判断




xoyozo 4 年前
2,883

在 ASP.NET Core 或 ASP.NET 5 中部署百度编辑器请跳转此文


本文记录百度编辑器 ASP.NET 版的部署过程,对其它语言版本也有一定的参考价值。

【2020.02.21 重新整理】


下载

从 GitHub 下载最新发布版本:https://github.com/fex-team/ueditor/releases

按编码分有 gbk 和 utf8 两种版本,按服务端编程语言分有 asp、jsp、net、php 四种版本,按需下载。


目录介绍

以 v1.4.3.3 utf8-net 为例,

ueditor 目录结构.png


客户端部署

本例将上述所有目录和文件拷贝到网站目录 /libs/ueditor/ 下。

当然也可以引用 CDN 静态资源,但会遇到诸多跨域问题,不建议。

在内容编辑页面引入:

<script src="/libs/ueditor/ueditor.config.js"></script>
<script src="/libs/ueditor/ueditor.all.min.js"></script>

在内容显示页面引入:

<script src="/libs/ueditor/ueditor.parse.min.js"></script>

如需修改编辑器资源文件根路径,参 ueditor.config.js 文件内顶部文件。(一般不需要单独设置)

如果使用 CDN,那么在初始化 UE 实例的时候应配置 serverUrl 值(即 controller.ashx 所在路径)。


客户端配置

初始化 UE 实例:

var ue = UE.getEditor('tb_content', {
    // serverUrl: '/libs/ueditor/net/controller.ashx', // 指定服务端接收文件路径
    initialFrameWidth: '100%'
});

其它参数见官方文档,或 ueditor.config.js 文件。


服务端部署

net 目录是 ASP.NET 版的服务端程序,用来实现接收上传的文件等功能。

本例中在网站中的位置是 /libs/ueditor/net/。如果改动了位置,那么在初始化 UE 的时候也应该配置 serverUrl 值。

这是一个完整的 VS 项目,可以单独部署为一个网站。其中:

net/config.json  服务端配置文件
net/controller.ashx  文件上传入口
net/App_Code/CrawlerHandler.cs  远程抓图动作
net/App_Code/ListFileManager.cs  文件管理动作
net/App_Code/UploadHandler.cs  上传动作

该目录不需要转换为应用程序。


服务端配置

根据 config.json 中 *PathFormat 的默认配置,一般地,上传的图片会保存在 controller.ashx 文件所在目录(即本例中的 /libs/ueditor/)的 upload 目录中:
/libs/ueditor/upload/image/
原因是 UploadHandler.cs 中 Server.MapPath 的参数是由 *PathFormat 决定的。

修改 config.json 中的 imagePathFormat 为例:

原值:"imagePathFormat": "upload/image/{yyyy}{mm}{dd}/{time}{rand:6}"

改为:"imagePathFormat": "/upload/ueditor/{yyyy}{mm}{dd}/{time}{rand:6}"

以“/”开始的路径在 Server.MapPath 时会定位到网站根目录。

此处不能以“~/”开始,因为最终在客户端显示的图片路径是 imageUrlPrefiximagePathFormat,若其中包含符号“~”就无法正确显示。

在该配置文件中查找所有 PathFormat,按相同的规则修改。


说到客户端的图片路径,我们只要将

原值:"imageUrlPrefix": "/ueditor/net/"

改为:"imageUrlPrefix": ""

即可返回客户端正确的 URL。

当然也要同步修改 scrawlUrlPrefix、snapscreenUrlPrefix、catcherUrlPrefix、videoUrlPrefix、fileUrlPrefix。


特殊情况,在复制包含图片的网页内容的操作中,若图片地址带“?”等符号,会出现无法保存到磁盘的情况,需要修改以下代码:

打开  CrawlerHandler.cs 文件,找到

ServerUrl = PathFormatter.Format(Path.GetFileName(this.SourceUrl), Config.GetString("catcherPathFormat"));

替换成:

ServerUrl = PathFormatter.Format(Path.GetFileName(SourceUrl.Contains("?") ? SourceUrl.Substring(0, SourceUrl.IndexOf("?")) : SourceUrl), Config.GetString("catcherPathFormat"));


如果你将图片保存到第三方图库,那么 imageUrlPrefix 值设为相应的域名即可,如:

改为:"imageUrlPrefix": "//cdn.***.com"

然后在 UploadHandler.cs 文件(用于文件上传)中找到

File.WriteAllBytes(localPath, uploadFileBytes);

在其下方插入上传到第三方图库的代码,以阿里云 OSS 为例:

// 上传到 OSS
client.PutObject(bucketName, savePath.Substring(1), localPath);

在 CrawlerHandler.cs 文件(无程抓图上传)中找到

File.WriteAllBytes(savePath, bytes);

在其下方插入上传到第三方图库的代码,以阿里云 OSS 为例:

// 上传到 OSS
client.PutObject(bucketName, ServerUrl.Substring(1), savePath);


最后有还有两个以 UrlPrefix 结尾的参数名 imageManagerUrlPrefix 和 fileManagerUrlPrefix 分别是用来列出上传目录中的图片和文件的,

对应的操作是在编辑器上的“多图上传”功能的“在线管理”,和“附件”功能的“在线附件”。

最终列出的图片路径是由 imageManagerUrlPrefiximageManagerListPath + 图片 URL 组成的,那么:

"imageManagerListPath": "/upload/ueditor/image",

"imageManagerUrlPrefix": "",

以及:

"fileManagerListPath": "/upload/ueditor/file",

"fileManagerUrlPrefix": "",

即可。

如果是上传到第三方图库的,且图库上的文件与本地副本是一致的,那么将 imageManagerUrlPrefix 和 fileManagerUrlPrefix 设置为图库域名,

服务端仍然以 imageManagerListPath 指定的路径来查找本地文件(非图库),但客户端显示图库的文件 URL。

因此,如果文件仅存放在图库上,本地没有副本的情况就无法使用该功能了。

综上,所有的 *UrlPrefix 应该设为一致。


另外记得配置不希望被远程抓图的域名,参数 catcherLocalDomain


服务端授权

现在来判断一下只有登录用户才允许上传。

首先打开服务端的统一入口文件 controller.ashx

继承类“IHttpHandler”改为“IHttpHandler, System.Web.SessionState.IRequiresSessionState”,即同时继承两个类,以便可使用 Session,
找到“switch”,其上插入:

if (用户未登录) { throw new System.Exception("请登录后再试"); }

即用户已登录或 action 为获取 config 才进入 switch。然后,

else
{
    action = new NotAllowedHandler(context);
}

这里的 NotAllowedHandler 是参照 NotSupportedHandler 创建的,提示语 state 可以是“登录后才能进行此操作。


上传目录权限设置

上传目录(即本例中的 /upload/ueditor/ 目录)应设置允许写入和禁止执行。


基本用法

设置内容:

ue.setContent("Hello world.");

获取内容:

var a = ue.getContent();

更多用法见官方文档:http://fex.baidu.com/ueditor/#api-common


其它事宜

配置上传附件的文件格式

找到文件:config.json,更改“上传文件配置”的 fileAllowFiles 项,

同时在 Web 服务器上允许这些格式的文件可访问权限。以 IIS 为例,在“MIME 类型”模块中添加扩展名。


遇到从客户端(......)中检测到有潜在危险的 Request.Form 值。参考此文


另外,对于不支持上传 .webp 类型的图片的问题,可以作以下修改:
config.json 中搜索“".bmp"”,替换为“".bmp", ".webp"
IIS 中选中对应网站或直接选中服务器名,打开“MIME 类型”,添加,文件扩展名为“.webp”,MIME 类型为“image/webp


最后,为了在内容展示页面看到跟编辑器中相同的效果,请参照官方文档引用 uParse

若有插入代码,再引用:
<link href="/lib/ueditor/utf8-net/third-party/SyntaxHighlighter/shCoreDefault.css" rel="stylesheet" />
<script src="/lib/ueditor/utf8-net/third-party/SyntaxHighlighter/shCore.js"></script>

其它插件雷同。


若对编辑器的尺寸有要求,在初始化时设置即可:

var ue = UE.getEditor('tb_content', {

  initialFrameWidth: '100%',
  initialFrameHeight: 320
});


图片等附件上传到阿里云 OSS 参考此文

xoyozo 8 年前
5,635

Apple’s newest devices feature the Retina Display, a screen that packs double as many pixels into the same space as older devices. For designers this immediately brings up the question, “What can I do to make my content look outstanding on these new iPads and iPhones?”. First there are a few tough questions to consider, but then this guide will help you get started making your websites and web apps look amazingly sharp with Retina images!

retina image comparison

Things to Consider When Adding Retina Images

The main issue with adding retina images is that the images are double as large and will take up extra bandwidth (this won’t be an issue for actual iOS apps, but this guide is covering web sites & web apps only). If your site is mostly used on-the-go over a 3G network it may not be wise to make all your graphics high-definition, but maybe choose only a select few important images. If you’re creating something that will be used more often on a WI-FI connection or have an application that is deserving of the extra wait for hi-res graphics these steps below will help you target only hi-res capable devices.

Simple Retina Images

The basic concept of a Retina image is that your taking a larger image, with double the amount of pixels that your image will be displayed at (e.g 200 x 200 pixels), and setting the image to fill half of that space (100 x 100 pixels). This can be done manually by setting the height and width in HTML to half the size of your image file.

<img src="my200x200image.jpg" width="100" height="100">

If you’d like to do something more advanced keep reading below for how you can apply this technique using scripting.

Creating Retina Icons for Your Website

When users add your website or web app to their homescreen it will be represented by an icon. These sizes for regular and Retina icons (from Apple) are as follows:
ios icon samples

iPhone 57 x 57
Retina iPhone 114 x 114
iPad 72 x 72
Retina iPad 144 x 144

For each of these images you create you can link them in the head of your document like this (if you want the device to add the round corners remove -precomposed):

<link href="touch-icon-iphone.png" rel="apple-touch-icon-precomposed" />
<link href="touch-icon-ipad.png" rel="apple-touch-icon-precomposed" sizes="72x72" />
<link href="touch-icon-iphone4.png" rel="apple-touch-icon-precomposed" sizes="114x114" />
<link href="touch-icon-ipad3.png" rel="apple-touch-icon-precomposed" sizes="144x144" />

If the correct size isn’t specified the device will use the smallest icon that is larger than the recommended size (i.e. if you left out the 114px the iPhone 4 would use the 144px icon).

Retina Background Images

Background images that are specified in your CSS can be swapped out using media queries. You’ll first want to generate two versions of each image. For example ‘bgPattern.png’ at 100px x 100px and ‘bgPattern@2x.png’ at 200px x 200px. It will be useful to have a standard naming convention such as adding @2x for these retina images. To add the new @2x image to your site simply add in the media query below (You can add any additional styles that have background images within the braces of the same media query):

.repeatingPattern {
     background: url(../images/bgPattern.png) repeat;
     background-size: 100px 100px;
}

@media only screen and (-webkit-min-device-pixel-ratio: 2) {
     .repeatingPattern {
          background: url(../images/bgPattern@2x.png) repeat;
     }
}

JavaScript for Retina Image Replacement

For your retina images that aren’t backgrounds the best option seems to be either creating graphics with CSS, using SVG, or replacing your images with JavaScript. Just like the background images, you’ll want to create a normal image and one ‘@2x’ image. Then with JavaScript you can detect if the pixel ratio of the browser is 2x, just like you did with the media query:

if (window.devicePixelRatio == 2) {

//Replace your img src with the new retina image

}

If you’re using jQuery you could quickly replace all your images like this very basic example below. It’s a good idea to add a class to identify the images with hi-res versions so you don’t replace any others by mistake. I’ve added a class=”hires” for this example. Also make sure you have the standard (non-retina) image height and width set in the HTML:

<img class="hires" alt="" src="search.png" width="100" height="100" />
<script type="text/javascript">
$(function () {

	if (window.devicePixelRatio == 2) {

          var images = $("img.hires");

          // loop through the images and make them hi-res
          for(var i = 0; i < images.length; i++) {

            // create new image name
            var imageType = images[i].src.substr(-4);
            var imageName = images[i].src.substr(0, images[i].src.length - 4);
            imageName += "@2x" + imageType;

            //rename image
            images[i].src = imageName;
          }
     }

});
</script>

Server-Side Retina Images

If you’d like to implement a server-side retina image solution, I recommend checking out Jeremy Worboys’ Retina Images (which he also posted in the comments below). His solution uses PHP code to determine which image should be served. The benefit of this solution is that it doesn’t have to replace the small image with the retina one so you’re using less bandwidth, especially if you have lots of images that you’re replacing.

Website Optimization for Retina Displays

If you’re looking for additional information on creating Retina images, I’ve recently had a short book published called Website Optimization for Retina Displays that covers a range of related topics. It contains some of what is above, but also includes samples for many different situations for adding Retina images. It explains the basics of creating Retina images, backgrounds, sprites, and borders. Then it talks about using media queries, creating graphics with CSS, embedding fonts, creating app icons, and more tips for creating Retina websites.

K
转自 Kyle Larson 12 年前
4,092

有时候已知一个 ID 的数组,需要读取这些记录内容,SQL 可以联接多个“或”关系去读取,或使用“In”语句,在 LINQ TO SQL 中可以这样来做:

List<int> ids = new List<int> { 1, 2, 3 };
List<string> tbs = db.dbTables.Where(c => ids.Contains<int>(c.ID)).ToList();
xoyozo 15 年前
4,085

我们继续讲解LINQ to SQL语句,这篇我们来讨论Group By/Having操作符和Exists/In/Any/All/Contains操作符。

Group By/Having操作符

适用场景:分组数据,为我们查找数据缩小范围。

说明:分配并返回对传入参数进行分组操作后的可枚举对象。分组;延迟

1.简单形式:

var q =
    from p in db.Products
    group p by p.CategoryID into g
    select g;

语句描述:使用Group By按CategoryID划分产品。

说明:from p in db.Products 表示从表中将产品对象取出来。group p by p.CategoryID into g表示对p按CategoryID字段归类。其结果命名为g,一旦重新命名,p的作用域就结束了,所以,最后select时,只能select g。当然,也不必重新命名可以这样写:

var q =
    from p in db.Products
    group p by p.CategoryID;

我们用示意图表示:

GroupBy分组统计示意图

如果想遍历某类别中所有记录,这样:

foreach (var gp in q)
{
    if (gp.Key == 2)
    {
        foreach (var item in gp)
        {
            //do something
        }
    }
}

2.Select匿名类:

var q =
    from p in db.Products
    group p by p.CategoryID into g
    select new { CategoryID = g.Key, g }; 

说明:在这句LINQ语句中,有2个property:CategoryID和g。这个匿名类,其实质是对返回结果集重新进行了包装。把g的property封装成一个完整的分组。如下图所示:

GroupBy分组匿名类示意图

如果想遍历某匿名类中所有记录,要这么做:

foreach (var gp in q)
{
    if (gp.CategoryID == 2)
    {
        foreach (var item in gp.g)
        {
            //do something
        }
    }
}

3.最大值

var q =
    from p in db.Products
    group p by p.CategoryID into g
    select new {
        g.Key,
        MaxPrice = g.Max(p => p.UnitPrice)
    };

语句描述:使用Group By和Max查找每个CategoryID的最高单价。

说明:先按CategoryID归类,判断各个分类产品中单价最大的Products。取出CategoryID值,并把UnitPrice值赋给MaxPrice。

4.最小值

var q =
    from p in db.Products
    group p by p.CategoryID into g
    select new {
        g.Key,
        MinPrice = g.Min(p => p.UnitPrice)
    };

语句描述:使用Group By和Min查找每个CategoryID的最低单价。

说明:先按CategoryID归类,判断各个分类产品中单价最小的Products。取出CategoryID值,并把UnitPrice值赋给MinPrice。

5.平均值

var q =
    from p in db.Products
    group p by p.CategoryID into g
    select new {
        g.Key,
        AveragePrice = g.Average(p => p.UnitPrice)
    };

语句描述:使用Group By和Average得到每个CategoryID的平均单价。

说明:先按CategoryID归类,取出CategoryID值和各个分类产品中单价的平均值。

6.求和

var q =
    from p in db.Products
    group p by p.CategoryID into g
    select new {
        g.Key,
        TotalPrice = g.Sum(p => p.UnitPrice)
    };

语句描述:使用Group By和Sum得到每个CategoryID 的单价总计。

说明:先按CategoryID归类,取出CategoryID值和各个分类产品中单价的总和。

7.计数

var q =
    from p in db.Products
    group p by p.CategoryID into g
    select new {
        g.Key,
        NumProducts = g.Count()
    };

语句描述:使用Group By和Count得到每个CategoryID中产品的数量。

说明:先按CategoryID归类,取出CategoryID值和各个分类产品的数量。

8.带条件计数

var q =
    from p in db.Products
    group p by p.CategoryID into g
    select new {
        g.Key,
        NumProducts = g.Count(p => p.Discontinued)
    };

语句描述:使用Group By和Count得到每个CategoryID中断货产品的数量。

说明:先按CategoryID归类,取出CategoryID值和各个分类产品的断货数量。 Count函数里,使用了Lambda表达式,Lambda表达式中的p,代表这个组里的一个元素或对象,即某一个产品。

9.Where限制

var q =
    from p in db.Products
    group p by p.CategoryID into g
    where g.Count() >= 10
    select new {
        g.Key,
        ProductCount = g.Count()
    };

语句描述:根据产品的―ID分组,查询产品数量大于10的ID和产品数量。这个示例在Group By子句后使用Where子句查找所有至少有10种产品的类别。

说明:在翻译成SQL语句时,在最外层嵌套了Where条件。

10.多列(Multiple Columns)

var categories =
    from p in db.Products
    group p by new
    {
        p.CategoryID,
        p.SupplierID
    }
        into g
        select new
            {
                g.Key,
                g
            };

语句描述:使用Group By按CategoryID和SupplierID将产品分组。

说明: 既按产品的分类,又按供应商分类。在by后面,new出来一个匿名类。这里,Key其实质是一个类的对象,Key包含两个Property:CategoryID、SupplierID。用g.Key.CategoryID可以遍历CategoryID的值。

11.表达式(Expression)

var categories =
    from p in db.Products
    group p by new { Criterion = p.UnitPrice > 10 } into g
    select g;

语句描述:使用Group By返回两个产品序列。第一个序列包含单价大于10的产品。第二个序列包含单价小于或等于10的产品。

说明:按产品单价是否大于10分类。其结果分为两类,大于的是一类,小于及等于为另一类。

Exists/In/Any/All/Contains操作符

适用场景:用于判断集合中元素,进一步缩小范围。

Any

说明:用于判断集合中是否有元素满足某一条件;不延迟。(若条件为空,则集合只要不为空就返回True,否则为False)。有2种形式,分别为简单形式和带条件形式。

1.简单形式:

仅返回没有订单的客户:

var q =
    from c in db.Customers
    where !c.Orders.Any()
    select c;

生成SQL语句为:

SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName],
[t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region],
[t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax]
FROM [dbo].[Customers] AS [t0]
WHERE NOT (EXISTS(
    SELECT NULL AS [EMPTY] FROM [dbo].[Orders] AS [t1]
    WHERE [t1].[CustomerID] = [t0].[CustomerID]
   ))

2.带条件形式:

仅返回至少有一种产品断货的类别:

var q =
    from c in db.Categories
    where c.Products.Any(p => p.Discontinued)
    select c;

生成SQL语句为:

SELECT [t0].[CategoryID], [t0].[CategoryName], [t0].[Description],
[t0].[Picture] FROM [dbo].[Categories] AS [t0]
WHERE EXISTS(
    SELECT NULL AS [EMPTY] FROM [dbo].[Products] AS [t1]
    WHERE ([t1].[Discontinued] = 1) AND 
    ([t1].[CategoryID] = [t0].[CategoryID])
    )

All

说明:用于判断集合中所有元素是否都满足某一条件;不延迟

1.带条件形式

var q =
    from c in db.Customers
    where c.Orders.All(o => o.ShipCity == c.City)
    select c;

语句描述:这个例子返回所有订单都运往其所在城市的客户或未下订单的客户。

Contains

说明:用于判断集合中是否包含有某一元素;不延迟。它是对两个序列进行连接操作的。

string[] customerID_Set =
    new string[] { "AROUT", "BOLID", "FISSA" };
var q = (
    from o in db.Orders
    where customerID_Set.Contains(o.CustomerID)
    select o).ToList();

语句描述:查找"AROUT", "BOLID" 和 "FISSA" 这三个客户的订单。 先定义了一个数组,在LINQ to SQL中使用Contains,数组中包含了所有的CustomerID,即返回结果中,所有的CustomerID都在这个集合内。也就是in。 你也可以把数组的定义放在LINQ to SQL语句里。比如:

var q = (
    from o in db.Orders
    where (
    new string[] { "AROUT", "BOLID", "FISSA" })
    .Contains(o.CustomerID)
    select o).ToList();

Not Contains则取反:

var q = (
    from o in db.Orders
    where !(
    new string[] { "AROUT", "BOLID", "FISSA" })
    .Contains(o.CustomerID)
    select o).ToList();

1.包含一个对象:

var order = (from o in db.Orders
             where o.OrderID == 10248
             select o).First();
var q = db.Customers.Where(p => p.Orders.Contains(order)).ToList();
foreach (var cust in q)
{
    foreach (var ord in cust.Orders)
    {
        //do something
    }
}

语句描述:这个例子使用Contain查找哪个客户包含OrderID为10248的订单。

2.包含多个值:

string[] cities = 
    new string[] { "Seattle", "London", "Vancouver", "Paris" };
var q = db.Customers.Where(p=>cities.Contains(p.City)).ToList();

语句描述:这个例子使用Contains查找其所在城市为西雅图、伦敦、巴黎或温哥华的客户。

总结一下这篇我们说明了以下语句:

Group By/Having 分组数据;延迟
Any 用于判断集合中是否有元素满足某一条件;不延迟
All 用于判断集合中所有元素是否都满足某一条件;不延迟
Contains 用于判断集合中是否包含有某一元素;不延迟

本系列链接:LINQ体验系列文章导航

LINQ推荐资源

LINQ专题:http://kb.cnblogs.com/zt/linq/ 关于LINQ方方面面的入门、进阶、深入的文章。
LINQ小组:http://space.cnblogs.com/group/linq/ 学习中遇到什么问题或者疑问提问的好地方。

转自 李永京 15 年前
4,104