In my below program I have to find the single duplicate number. For example (from the series 3, 5, 3, 2, 7, 7, 5, 6
) if 3
is repeated then program should exit and return 3
. If not then go for next number 5
, if it's repeated then should exits and return 5
.
I am getting all repeated numbers 3,5,7
but I want to find the single number which is repeated first. How should I get this?
class Program
{
private string checkduplicate()
{
List<int> list = new List<int>() { 3, 5, 3, 2, 7, 7, 5, 6 };
IEnumerable<int> duplicates = list.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(x => x.Key);
return String.Join(",", duplicates);
//var list = new List<int>() { 3, 5, 3, 2, 7, 7, 5, 6 };
//list.GroupBy(n => n).Any(c => c.Count() > 1);
}
static void Main(string[] args)
{
Program p = new Program();
Console.WriteLine(p.checkduplicate());
Console.ReadLine();
}
}
CodePudding user response:
There's another option without GroupBy
:
private string checkduplicate()
{
List<int> list = new List<int>() { 3, 5, 3, 2, 7, 7, 5, 6 };
return list.Where((num, ind) => list.LastIndexOf(num) > ind).FirstOrDefault().ToString();
}
CodePudding user response:
If you want just first item, you don't need the list, since it's always gonna be just one number.
So, instead of IEnumerable<int> duplicates = ...
go with int duplicate = ...
, and just put FirstOrDefault()
after the select
in your LINQ.
You can change your return value as well, since there is no need to join
anything.
public class Program
{
public static void Main()
{
Program p = new Program();
Console.WriteLine(p.checkduplicate());
Console.ReadLine();
}
private string checkduplicate()
{
List<int> list = new List<int>() { 3, 5, 3, 2, 7, 7, 5, 6 };
int duplicates = list.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(x => x.Key).FirstOrDefault();
return duplicates.ToString();
//var list = new List<int>() { 3, 5, 3, 2, 7, 7, 5, 6 };
//list.GroupBy(n => n).Any(c => c.Count() > 1);
}
}
CodePudding user response:
Find your duplicates, filter them to > 1 and then grab the first item which has any values in your duplicate list.
private string checkduplicate()
{
var list = new List<int>() { 3, 5, 3, 2, 7, 7, 5, 6 };
var duplicates = list
.GroupBy(x => x)
.Where(g => g.Count() > 1);
return list
.First(item => duplicates.Any(dup => dup.Key == item))
.ToString();
}
CodePudding user response:
You can use FirstOrDefault() or SingleOrDefault() for this. Modify the checkDuplicate() method as below.
private string checkduplicate()
{
List<int> list = new List<int>() { 3, 5, 3, 2, 7, 7, 5, 6 };
int duplicate = list.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(x => x.Key).FirstOrDefault();
return duplicate.ToString();
}