Linq - 集团的第一个名字

dot*_*oob 6 c# linq asp.net

我正在使用Entity Framework 6作为我的数据源.

我创建了一个页面,用他们名字的第一个字母列出供应商,所以首先我们有'A',然后'B'等等.

为了做到这一点,我使用了2个ListView对象 - 它可以很容易地成为一个Repeater,但这并不重要.

虽然我的供应商列表并不广泛,但我用来获取数据的方法非常昂贵,因为在数据绑定期间我必须将其称为27次.我很确定有更好的方法可以解决这个问题,但我不知道我在Linq周围的方式.

我认为必须有一种方法来分组数据,然后循环遍历组的内容.

这是重要的代码.linq用于检索子数据和数据绑定代码:

    public static IEnumerable<Supplier> StartsWith(string firstLetter)
    {
        return Select() // select simply returns all data for the entity
            .Where(x => x.Name.StartsWith(firstLetter, StringComparison.OrdinalIgnoreCase));
    }

    protected void ListViewAtoZ_ItemDataBound(object source, ListViewItemEventArgs e)
    {
        var item = e.Item;

        if (item.ItemType == ListViewItemType.DataItem)
        {
            var alphanumeric = (string)item.DataItem;

            var h2 = item.GetControl<HtmlGenericControl>("HtmlH2", true);
            h2.InnerText = alphanumeric;

            var childView = item.GetControl<ListView>("ListViewStartsWith", true);
            childView.DataSource = LenderView.StartsWith(alphanumeric);
            childView.DataBind();
        }
    }

    protected void ListViewStartsWith_ItemDataBound(object source, ListViewItemEventArgs e)
    {
        var item = e.Item;

        if (item.ItemType == ListViewItemType.DataItem)
        {
            var supplier = (Supplier)item.DataItem;

            var litName = item.GetControl<Literal>("LiteralName", true);
            litName.Text = supplier.Name;
        }
    }

    void LoadData()
    {
        var alphanumerics = new string[]
        {
            "0 - 9","A","B","C","D","E","F","G","H","I","J","K","L",
            "M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
        }; 

        ListViewAtoZ.DataSource = alphanumerics;
        ListViewAtoZ.DataBind();
    }
Run Code Online (Sandbox Code Playgroud)

Sar*_*thy 13

您可以使用以下内容进行分组并获取项目的子列表.

Select().GroupBy(x => x.Name.Substring(0,1).ToUpper(), (alphabet, subList) => new { Alphabet = alphabet, SubList = subList.OrderBy(x => x.Name).ToList() })
                .OrderBy(x => x.Alphabet)
Run Code Online (Sandbox Code Playgroud)

上面的代码应该在一次迭代中对所有数据进行分组.该代码适用于LINQ对象.对于LINQ实体也应该以相同的方式工作.