[c#] linq将一个stringarray排成vars [英] [c#]linq sort a stringarray into vars

查看:63
本文介绍了[c#] linq将一个stringarray排成vars的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串数组。每个字符串包含由,分隔的多个变量。我记得几年前当我做VB.NET时,LINQ有一种方法可以将数组排序到相应的变量中,选择你需要的变量并随意使用它们。例如:

I have an Array of strings. Each string contains multiple vars separated by a ",". I remember years ago when I did VB.NET there was a way to LINQ sort an array into corresponding vars, select which ones you need and use them however you like. For example:

Dim facultyQuery = From member In members
                          Let column = member.Split(","c)
                          Let name = column(0)
                          Let points = CInt(column(1))
                          Select name, points
                          Order By name

For Each member In facultyQuery
            strTemp = member.name
            Exit For
        Next



对于我在VB中制作的下拉菜单,这是一个简单的LINQ排序。现在我想在C#中做同样的事情。我的目标是对数据进行排序,取出我不需要的东西,并将我需要的东西放入DataGridView控件中进行显示。以下是其中一个字符串的示例:


That was a simple LINQ sort for a drop down I made in VB. Now I'm looking to do the same in C#. My goal is to sort the data, take out what I don't need and put what I need into DataGridView control for display. Here's a sample of one of the strings:

CAR_Sales_Default,2,0,2,0,00:24:56,00:00:00,0,69,-LWC_BG:#cc0000,-LCB_BG:#00cc00



我需要整理名称,第3个数字,2次及其对应的背景,并将其放入DataGridView。我如何在C#中使用LINQ来做到这一点?



编辑:

使用类似这样的东西工作了


I need to sort out the name, the 3rd number, the 2 times and their corresponding background and put that into a DataGridView. How can I do that using LINQ in C#?


Got it working using something like this

char[] splitChars = new char[] { ',' };

            var query = from data in tr
                        let columns = data.Split(splitChars, StringSplitOptions.None)
                        select new
                        {
                            qNames = columns[0].Substring(0, columns[0].Length - 6),
                            totCallW8 = Int32.Parse(columns[3]),
                            longW8InCall = columns[5],
                            longW8CallBack = columns[6],
                            BGtrLWC = columns[9].Substring(8),
                            BGtrLCB = columns[10].Substring(8),
                        }
                            into qSort
                            orderby qSort.qNames
                            select qSort;

            foreach (var result in query)
            {
                if (result.qNames.Contains(system))
                {
                    
                    dataGridView1.Rows.Add(result.qNames, result.totCallW8, result.longW8InCall, result.longW8CallBack);

                    dataGridView1.CurrentCell = dataGridView1.Rows[count].Cells[2];

                    dataGridView1[2, dataGridView1.CurrentRow.Index].Style.BackColor = ColorTranslator.FromHtml(result.BGtrLWC);
                    dataGridView1[3, dataGridView1.CurrentRow.Index].Style.BackColor = ColorTranslator.FromHtml(result.BGtrLCB);

                    count++;
                }
            }





我的尝试:



我可以使用for循环并手动拆分它们并将它们添加到GridView但这将花费太长时间。我在ListView中显示所有数据的第一种方法是for循环,这使得运行时非常糟糕。



What I have tried:

I could use a for loop and manually split them and add them to the GridView but that will take too long. My first approach to even displaying all the data in a ListView was a for loop and that made the run time very bad.

推荐答案

如果你想使用相同的方法,这就是你在C#中的表现:

If you want to use the same approach, this is how you could do it in C#:
// this declaration as a class member:
static char[] splitChars = new char[] { ',' };

// just some sample data:
string[] rows = new string[] { "name2,1,2,3", "name1,3,4,5" };

var query = from row in rows
            let columns = row.Split(splitChars, StringSplitOptions.None)
            select new
            {
                name = columns[0],
                points = Int32.Parse(columns[1]),
            }
            into results
            orderby results.name
            select results;

foreach (var result in query)
{
    Console.WriteLine(String.Format("Name: {0}, Points: {1}", result.name, result.points));
}





但您可以考虑使用CSV阅读器。这是一个很好的例子:快速CSV阅读器 [ ^ ]





编辑:

我错过了你要在DataGridView中显示结果的部分。到达那里的最快方法是:



But you might consider using a CSV reader instead. Here's an excellent one: A Fast CSV Reader[^]



I missed the part that you want to display the result in a DataGridView. The fastest way to get there would be this:

MydataGridView.DataSource = query.ToList();



但是,如果你想修改DGV中的值,然后将它们读回到某个地方,我建议使用DataTable或常规类来代替结果而不是上面我的示例中编译器构造的匿名类型 - 所以请改为:


However, if you want to modify the values in the DGV and then read them back into somewhere I would recommend using either a DataTable or a regular class for the results instead of the anonymous type constructed by the compiler in my sample above - so something like this instead:

public class ResultRow
{
    public string Name { get; private set; } // non-editable in DGV
    public int Points { get; set; }          // editable in DGV

    public ResultRow(string name, int points)
    {
        Name = name;
        Points = points;
    }
}

// as a class member:
List<ResultRow> ResultsList;


var query2 = from row in rows
             let columns = row.Split(splitChars, StringSplitOptions.None)
             select new ResultRow(columns[0], Int32.Parse(columns[1])) into results
             orderby results.Name
             select results;

ResultsList = query2.ToList();

MyDataGridView.DataSource = ResultsList;





编辑2 (评论后) :

基于从源数据中读取的值添加单元格着色的示例代码 - 可能不是您希望实现的100%但我认为您会理解:



Edit 2 (after comment):
Sample code to add cell coloring based on values read from your source data - maybe not 100% what you want to achieve but I think you will get the idea:

public partial class Form2 : Form
{
    static char[] splitChars = new char[] { ',' };

    BindingList<ResultRow> ResultsBindingList;

    public class ResultRow
    {
        public string Name { get; private set; } // non-editable in DGV
        public int Points { get; set; }          // editable in DGV
        public Color CellColor { get; private set; }

        public ResultRow(string name, int points, Color cellColor)
        {
            Name = name;
            Points = points;
            CellColor = cellColor;
        }
    }

    public Form2()
    {
        InitializeComponent();

        string[] rows = new string[] { "name2,1,2,3,#cc0000", "name1,3,4,5,#00cc00" };

        var query = from row in rows
            let columns = row.Split(splitChars, StringSplitOptions.None)
            let name = columns[0]
            let points = Int32.Parse(columns[1])
            let color = System.Drawing.ColorTranslator.FromHtml(columns[4])
            select new ResultRow(name, points, color) into results
            orderby results.Name
            select results;

        ResultsBindingList = new BindingList<ResultRow>(query.ToList());

        MyDataGridView.DataSource = ResultsBindingList;

        MyDataGridView.Columns["CellColor"].Visible = false;

        MyDataGridView.CellFormatting += MyDataGridViewCellFormatting;
    }

    private void MyDataGridViewCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        e.CellStyle.BackColor = (Color)MyDataGridView["CellColor", e.RowIndex].Value;
    }

    private void AddRowButtonClick(object sender, EventArgs e)
    {
        ResultsBindingList.Add(new ResultRow("", 0, Color.Yellow));
    }
}


Linq不会加速这个过程 - 它也是一个循环,但是它是延迟的执行当实际需要数据而不是执行原始查询代码时在幕后发生的循环。



如果运行时间非常糟糕将数据加载到任何显示控件时,这通常表明您试图显示太多信息。永远不要加载超过100行的控件,最好永远不要超过20行 - 对于用户而言,它既慢又无法使用,因为他无法在其他数据的泥沼中找到他需要查看的内容。对它进行分页,过滤它,但不要只是将它全部扔给用户!
Linq won't speed up the process that much - it's a loop as well, but it's a "deferred execution" loop that happens behind the scenes when the data is actually required instead of when the original query code is executed.

And if the run time is "very bad" when loading your data into any display control, that's normally a sign that you are trying to display far too much information. Never load a control with more than 100 rows, and preferably never with more than 20 or so - above that it's both slow and unusable for the user as he can't find what he needs to look at in the morass of the other data. Page it, filter it, but never just throw it all at the user!


这篇关于[c#] linq将一个stringarray排成vars的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆