简体   繁体   English

如何从列表中获取重复的项目子字符串? c#

[英]How to get duplicated item substrings from a list? c#

lets say I have a list with items:假设我有一个包含项目的列表:

TEST1 -- 99,56$ -- 25 PCS  -- 10:56
TEST2 -- 56,57$ -- 57 PCS  -- 11:01
TEST3 -- 56,57$ -- 43 PCS  -- 11:06
TEST4 -- 56,57$ -- 59 PCS  -- 11:33
TEST3 -- 56,57$ -- 43 PCS  -- 11:06
TEST3 -- 56,57$ -- 43 PCS  -- 11:06
TEST1 -- 58,98$ -- 25 PCS  -- 11:45

And I would want to get only duplicated items where the NAME Value (NAME Value is the first part where TEST is) and PCS Value is the same, into a new list, so my desired new list output would be:我只想将 NAME 值(NAME 值是 TEST 所在的第一部分)和 PCS 值相同的重复项目放入新列表中,因此我想要的新列表 output 将是:

TEST3 -- 56,57$ -- 43 PCS  -- 11:06
TEST1 -- 99,56$ -- 25 PCS  -- 10:56
TEST1 -- 58,98$ -- 25 PCS  -- 11:45

MY CURRENT CODE:我当前的代码:

namespace Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

   

        private void button1_Click_1(object sender, EventArgs e)
        {
            List<string> listwithbuys = new List<string>(new string[] { 
"TEST1 -- 99,56$ -- 25 PCS  -- 10:56",
"TEST2 -- 56,57$ -- 57 PCS  -- 11:01",
"TEST3 -- 56,57$ -- 43 PCS  -- 11:06",
"TEST4 -- 56,57$ -- 59 PCS  -- 11:33",
"TEST3 -- 56,57$ -- 43 PCS  -- 11:06",
"TEST3 -- 56,57$ -- 43 PCS  -- 11:06",
"TEST1 -- 58,98$ -- 25 PCS  -- 11:45" });
             List<String> duplicates = listwithbuys.GroupBy(x => x)
                             .Where(g => g.Count() > 1)
                             .Select(g => g.Key)
                             .ToList();
           listbox1.DataSource = duplicates;
        }
    }
}

Above code would print me:上面的代码会打印我:

TEST3 -- 56,57$ -- 43 PCS  -- 11:06

Which is not my goal, like I said I only want it to give me duplicated items where NAME and PCS Value are the same.这不是我的目标,就像我说的那样,我只希望它给我重复的项目,其中 NAME 和 PCS Value 相同。 Thanks to anyone trying to help:)感谢任何试图提供帮助的人:)

Can you please try this code, let me know if have any queries.你能试试这个代码吗,如果有任何疑问,请告诉我。

List<string> listwithbuys = new List<string>(new string[] {
"TEST1 -- 99,56$ -- 25 PCS  -- 10:56",
"TEST2 -- 56,57$ -- 57 PCS  -- 11:01",
"TEST3 -- 56,57$ -- 43 PCS  -- 11:06",
"TEST4 -- 56,57$ -- 59 PCS  -- 11:33",
"TEST3 -- 56,57$ -- 43 PCS  -- 11:06",
"TEST3 -- 56,57$ -- 43 PCS  -- 11:06",
"TEST1 -- 58,98$ -- 25 PCS  -- 11:45" });
            List<String> duplicates = listwithbuys.GroupBy(x => new { Name = x.Split(new string[] { " -- " }, StringSplitOptions.None)[0], 
                                                                     PCS = x.Split(new string[] { " -- " }, StringSplitOptions.None)[2] })
                            .Where(g => g.Count() > 1)
                            .Select(g => g.LastOrDefault())
                            .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM