您最喜欢的 LINQ 到对象查询

发布于 2024-07-13 07:56:35 字数 1432 浏览 10 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

那片花海 2024-07-20 07:56:35

过滤掉列表中的空项目。

var nonnull = somelist.Where(a => a != null);

创建一个字典,其中键是属性的值,值是该属性在列表中出现的次数。

var countDictionary = somelist
    .GroupBy(a => a.SomeProperty)
    .ToDictionary(g => g.Key, g => g.Count());

Filter out null items in a list.

var nonnull = somelist.Where(a => a != null);

Create a dictionary where the key is the value of a property, and the value is the number of times that property appears in the list.

var countDictionary = somelist
    .GroupBy(a => a.SomeProperty)
    .ToDictionary(g => g.Key, g => g.Count());
我的鱼塘能养鲲 2024-07-20 07:56:35

LINQ 只是在 C#/VB 上添加了一些函数式编程概念。 因此,是的,大多数事情都会变得容易得多。 C# 2.0 实际上有一些这样的功能——例如,请参阅 List 方法。 (尽管 C# 2.0 中的匿名方法语法过于冗长。)

下面是一个小例子:

static readonly string badChars = "!@#$%^&*()";
bool IsUserNameValid(string userName) {
  return userName.Intersect(badChars).Any();
}

LINQ is merely the addition of some functional programming concepts to C#/VB. Hence, yes, most things tend to get much easier. C# 2.0 actually had some of this -- see the List methods, for instance. (Although, anonymous method syntax in C# 2.0 was too verbose.)

Here's one little example:

static readonly string badChars = "!@#$%^&*()";
bool IsUserNameValid(string userName) {
  return userName.Intersect(badChars).Any();
}
与他有关 2024-07-20 07:56:35

示例 1

返回包含本地网络中所有可用 SQL Server 实例名称的列表

private List<string> GetServerNames()
{
    return SqlDataSourceEnumerator.Instance.GetDataSources().Rows.
        Cast<DataRow>().
        Select
        (
            row => row["ServerName"].ToString() + 
                  (row["InstanceName"] != DBNull.Value ? "\\" + row["InstanceName"].ToString() : "") + 
                  (row["Version"] != DBNull.Value ? " (" + row["Version"].ToString().Substring(0, 3) + ")" : "")
        ).
        OrderBy(s => s).
        ToList();
}

示例 2

为新文件生成未使用的名称

private string NewName(string newNamePrefix, List<string> existingFileNames)
{
    return newNamePrefix + 
        (existingFileNames.
            Select
            (
                n =>
                {
                    if (n.StartsWith(newNamePrefix))
                    {
                        int i;
                        if (int.TryParse(n.Replace(newNamePrefix, ""), out i))
                            return i;
                    }

                    return 0;
                }
            ).
            OrderBy(i => i).
            Last() + 1
        );
}

Example 1

Returns list with names of all available instances of SQL Server within the local network

private List<string> GetServerNames()
{
    return SqlDataSourceEnumerator.Instance.GetDataSources().Rows.
        Cast<DataRow>().
        Select
        (
            row => row["ServerName"].ToString() + 
                  (row["InstanceName"] != DBNull.Value ? "\\" + row["InstanceName"].ToString() : "") + 
                  (row["Version"] != DBNull.Value ? " (" + row["Version"].ToString().Substring(0, 3) + ")" : "")
        ).
        OrderBy(s => s).
        ToList();
}

Example 2

Generates not used name for new file

private string NewName(string newNamePrefix, List<string> existingFileNames)
{
    return newNamePrefix + 
        (existingFileNames.
            Select
            (
                n =>
                {
                    if (n.StartsWith(newNamePrefix))
                    {
                        int i;
                        if (int.TryParse(n.Replace(newNamePrefix, ""), out i))
                            return i;
                    }

                    return 0;
                }
            ).
            OrderBy(i => i).
            Last() + 1
        );
}
苏辞 2024-07-20 07:56:35

我有两个我喜欢的非常荒谬但优雅的例子,

public static IEnumerable<bool> Information(this byte x)
{
    return Enumerable.Range(0, 8).Select(i => ((x >> i) & 1) == 1);
}

public static IEnumerable<bool> Information(this IEnumerable<byte> xs)
{
    return xs.SelectMany(Information);
}

尽管它们被封装为查询运算符,因此您可以重用它们,例如用于二进制解析

var n = bytes.Information().Skip(3).Take(16).ToInt();

I have two nicely absurd but elegant examples that I love

public static IEnumerable<bool> Information(this byte x)
{
    return Enumerable.Range(0, 8).Select(i => ((x >> i) & 1) == 1);
}

public static IEnumerable<bool> Information(this IEnumerable<byte> xs)
{
    return xs.SelectMany(Information);
}

Albeit these are encapsulated as query operators so you can reuse them, e.g. for binary parsing

var n = bytes.Information().Skip(3).Take(16).ToInt();
念﹏祤嫣 2024-07-20 07:56:35

如果您有一个分隔的 Name=Value 字符串,例如 "ID=2;Name=James;Age=32;" 并且您希望将其快速转换为字典, 您可以使用:

var dict = value.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries)
    .Select(str => str.Split('='))
    .ToDictionary(pair => pair[0], pair => pair[1]);

If you have a delimited Name=Value string, such as "ID=2;Name=James;Age=32;" and you want to turn this into a dictionary quickly, you can use:

var dict = value.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries)
    .Select(str => str.Split('='))
    .ToDictionary(pair => pair[0], pair => pair[1]);
罪#恶を代价 2024-07-20 07:56:35

如果您有一个列表(即List调色板),其中包含包含另一个列表(即Palette.Colors)的对象,并且希望将所有这些子列表展平为一:

List<Color> allColors = palettes.SelectMany(p => p.Colors);

If you have a list (i.e. List<Palette> palettes) that contains objects which contains another list (i.e. Palette.Colors) and want to flatten all those sub-lists into one:

List<Color> allColors = palettes.SelectMany(p => p.Colors);
若无相欠,怎会相见 2024-07-20 07:56:35

当我移植代码时,我喜欢在文本上使用 LINQ:

例如:

String.Join("\n", @"some VB6 code
    that I could refactor automatically
    if FindAndReplace were a bit more powerfully
    And I don't want to refactor by hand".Split('\n').Trim().Select(line =>
    {
        if(line.Contains("FindAndReplace") && !line.StartsWith("//"))
        {
            return line.Split(" ").Last();
        }
        else
        {
            return String.Join("_", line.Split(" ").Take(3));
        }
    });

您明白了。 Linq 让我能够将 C# 的全部功能应用于文本转换。 通常,当我有一种语言的代码,我想以复杂的方式提取和操作时,我会使用它,我将文本单独放入 LinqPad 中,并对引号进行“查找-替换”,用双引号替换它们,然后我用 @"..." 包围它并开始工作。 我通常可以在 30 秒左右完成大量代码转换。

I like to use LINQ on text when I'm porting code:

For example:

String.Join("\n", @"some VB6 code
    that I could refactor automatically
    if FindAndReplace were a bit more powerfully
    And I don't want to refactor by hand".Split('\n').Trim().Select(line =>
    {
        if(line.Contains("FindAndReplace") && !line.StartsWith("//"))
        {
            return line.Split(" ").Last();
        }
        else
        {
            return String.Join("_", line.Split(" ").Take(3));
        }
    });

You get the idea. Linq lets me apply the full power of C# to text transformation. Typically I use it when I have code in one language that I want to extract and manipulate in a complex manner, I throw the text alone in LinqPad and do a "find-replace" on quotation marks, replacing them with double quotation marks, then I surround it by @"..." and get to work. I can usually do massive code transformations in 30 seconds or so.

或十年 2024-07-20 07:56:35

我最喜欢的是以下 Linq 示例,用于从 Northwind 数据库:

void Main()
{

// Demonstrates dynamic ordering

var SortExpression = "Total"; // choose ProductName or Total
var sortAscending = true; // choose true for ascending, false for descending

// the query to sort
var data = (from pd in Products
                    join od in OrderDetails on pd.ProductID equals od.ProductID into DetailsByProduct
                    select new { ProductName = pd.ProductName, Total = DetailsByProduct.Count()}).ToList();

// the data source you can use for data binding                     
var ds= (sortAscending) 
    ? data.OrderBy(x => x.GetType().GetProperty(SortExpression).GetValue(x, null))
    : data.OrderByDescending(x => x.GetType().GetProperty(SortExpression).GetValue(x, null));

ds.Dump();
}

它允许您通过简单地在变量 SortExpression 中指定字段并在变量 中指定排序顺序来动态排序升序排序。

通过使用.Take(x).Skip(y),您还可以轻松地实现分页

My favorite is the following Linq example for dynamically sorting a SQL table from the Northwind database:

void Main()
{

// Demonstrates dynamic ordering

var SortExpression = "Total"; // choose ProductName or Total
var sortAscending = true; // choose true for ascending, false for descending

// the query to sort
var data = (from pd in Products
                    join od in OrderDetails on pd.ProductID equals od.ProductID into DetailsByProduct
                    select new { ProductName = pd.ProductName, Total = DetailsByProduct.Count()}).ToList();

// the data source you can use for data binding                     
var ds= (sortAscending) 
    ? data.OrderBy(x => x.GetType().GetProperty(SortExpression).GetValue(x, null))
    : data.OrderByDescending(x => x.GetType().GetProperty(SortExpression).GetValue(x, null));

ds.Dump();
}

It allows you to dynamically sort by simply specifying a field in the variable SortExpression and a sort order in the variable sortAscending.

By using .Take(x) and .Skip(y) you can as well implement paging easily.

勿挽旧人 2024-07-20 07:56:35

让我开始了,太棒了!

var myList = from list in myObjectList select list

Got me started and its awesome!

var myList = from list in myObjectList select list
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文