如何删除列表中只有一个的项目? [英] How remove items who is only one in List?

查看:99
本文介绍了如何删除列表中只有一个的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好b $ b

我想从列表中获取数据,这会花费更多时间。

例如我有一个列表,其中包含项目1,2,5,2,8,7,8,2

我只想要更多时间的项目2,2,8,8,2


是这个方法还是?



我创造了这个方式...

foreach和List.Contains和最后一步添加到新列表。



谢谢

解决方案

您好,



<前lang =cs> var input = new List< int>(){ 1 2 5 2 8 7 8 2 };
var output =( from x in 输入
其中 input.Count(c = > c == x) > 1
选择 x)的.ToList();

Console.WriteLine( string .Join( ,input));
Console.WriteLine( string .Join( ,输出));





我希望它可以帮到你。


< blockquote>由于您标记为LINQ,这是一个LINQ方法解决方案:



 List< int> data =   1,2,5,2,8,7,8,2 .Split( ' ,')。选择(s = >   int  .Parse(s))。ToList();  //  设置输入列表 

List< int>重复= data.GroupBy(i = > i)。其中(g = > g.Count ()!= 1 )。选择(g = > g.Key)。ToList(); // 所以它只完成一次。
List< int> duplicates = data.Where(i = > repeats.Contains(i))。ToList();

foreach int i in duplicates)Console.WriteLine(i);
< / int >


你好,

即使尝试以下

列表与LT; INT> list =  new 列表< int>(){ 1  3  3  4  5  6  6  7  8 }; 
var x = list.GroupBy(x => x).FirstOrDefault(g => g.Count()> 1).Key; // C#3


Hi
I would like get data from list, which is used more time.
e.g. I have a list who contains items 1,2,5,2,8,7,8,2
I want only item who is more time 2,2,8,8,2

Is for this some method or?

I create my way this...
foreach and List.Contains and last step add to new List.

Thank you

解决方案

Hello,

var input = new List<int>() { 1, 2, 5, 2, 8, 7, 8, 2 };
var output = (from x in input
                where input.Count(c => c == x) > 1
                select x).ToList();

Console.WriteLine(string.Join(", ", input));
Console.WriteLine(string.Join(", ", output));



I hope it help you.


Since you tagged as LINQ, here is a LINQ method solution:

            List<int> data = "1,2,5,2,8,7,8,2".Split(',').Select(s => int.Parse(s)).ToList();  //Setup input list

            List<int> repeats = data.GroupBy(i => i).Where(g => g.Count() != 1).Select(g => g.Key).ToList(); // So it's done once only.
            List<int> duplicates = data.Where(i => repeats.Contains(i)).ToList();

            foreach (int i in duplicates) Console.WriteLine(i);
</int>


Hello ,
Even Try The Following

List<int> list = new List<int>() { 1, 3, 3, 4, 5, 6, 6, 7, 8 };
var x = list.GroupBy(x=>x).FirstOrDefault(g=>g.Count()>1).Key;//C#3


这篇关于如何删除列表中只有一个的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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