需要 Char[] 数组帮助

发布于 2024-11-02 13:38:25 字数 474 浏览 0 评论 0原文

我有一个数据库中包含公司名称的对象集合。

我需要获取所有不同标题的第一个字母 (char[]) (.Distinct())。

目前我有类似的东西:

public char[] GetBrandsAlphabet()
    {
        using (var dc = ReturnContext())
        {
            var resultBrands =
                from brands in dc.Brands
                orderby brands.Title ascending
                select brands.Title.ToCharArray()[0];

            char[] ret = new char[resultBrands.Distinct().Count()];



        }
    }

I have a collection of objects from a database that holds the titles of companies.

I need to get the first letters (char[]) of all the titles distincted (.Distinct()).

Currently I have something like:

public char[] GetBrandsAlphabet()
    {
        using (var dc = ReturnContext())
        {
            var resultBrands =
                from brands in dc.Brands
                orderby brands.Title ascending
                select brands.Title.ToCharArray()[0];

            char[] ret = new char[resultBrands.Distinct().Count()];



        }
    }

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

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

发布评论

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

评论(3

遥远的她 2024-11-09 13:38:25

将最后一行替换为:

char[] ret = resultBrands.Distinct().ToArray();

或者,嘿,用这个衬垫替换其他所有内容怎么样?

char[] ret = (from brands in dc.Brands 
              select brands.Title.ToUpper[0]).Distinct().OrderBy(c => c).ToArray();

ToUpper 保证最终数组中不会同时包含“A”和“a”。

Replace the last line with this:

char[] ret = resultBrands.Distinct().ToArray();

Or, hey, how about this one liner to replace everything else?

char[] ret = (from brands in dc.Brands 
              select brands.Title.ToUpper[0]).Distinct().OrderBy(c => c).ToArray();

The ToUpper guarantees that you won't have both 'A' and 'a' in your final array.

朕就是辣么酷 2024-11-09 13:38:25
return resultBrands.Distinct().ToArray();

但是,这可能无法完全按照您想要的方式工作,因为原则上 Distinct 可以更改元素的顺序。我将从 sql 语句中删除 orderby 语句并使用:

return resultBrands.Distinct().OrderBy(c => c).ToArray();
return resultBrands.Distinct().ToArray();

However, this might not work exactly the way that you want, since Distinct could, in principle, change the ordering of the elements. I would remove the orderby statement from the sql statement and use:

return resultBrands.Distinct().OrderBy(c => c).ToArray();
安人多梦 2024-11-09 13:38:25

好的其他人已经说过了。不过,您可以改进这部分:

  var resultBrands =
                from brands in dc.Brands
                orderby brands.Title ascending
                select brands.Title[0];

字符串已经可以像字符数组一样通过索引寻址,您不需要转换它。

OK What others already said. You can improve this part though:

  var resultBrands =
                from brands in dc.Brands
                orderby brands.Title ascending
                select brands.Title[0];

A string is already addressable by index like a char array, you don't need to convert it.

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