5

I used .Net framwork 4.0 with WinForm application component DataGridView and set DataSource with DataTable.Then there's a button to add row into DataGridView.

That code like this.

gridTable = (DataTable)dgrMainGrid.DataSource; 
DataRow dr = gridTable.NewRow();

Before adding New Row into DataTable I checked if there's a duplicate row.To do that I used this LINQ Query.

//Item Code cannot duplicate
var results = from itmCode in gridTable.AsEnumerable()
              where (itmCode.Field<string>("Item Code") == txtGrdItmLoc.Text)
              select itmCode;

There after how I check the duplicate rows available or not in the data table?

if(//doWhatever function here ){
  //if there's duplicate row values 
  isNotDuplicate = false;
}
else{
  isNotDuplicate=true;
}

Before go to following step I need to get is there a duplicate or not and set it into isNotDuplicate variable or similar thing to check that. so i think to count the results rows but there's no such function to count 'var results`, Any possibility to do that?

if (!isDuplicate)
{
     dr["#"] = true;
     dr["Item Code"] = lSysItemCode;
     dr["Stock Code"] = txtGdrItmItemLoc.Text;
     dr["Brand"] = txtGrdItmBrand.Text;
     dr["Model No"] = cmbGrdItmModel.SelectedValue.ToString();
     gridTable.Rows.Add(dr);
     dgrMainGrid.DataSource = gridTable;
}

I can use for loop with DataTable and check whether it's contain new value that equals to "Item Code" but I looking alternative method with linq.

Simply I'm looking replacement for this by using linq.

foreach (DataRow r in gridTable.Rows) {
             if (r["Item Code"].ToString() == txtGrdItmLoc.Text) {
                    isDuplicate = true;
             }
        }

Sample Project : http://1drv.ms/1K4JnHt

Sample Code : http://pastebin.com/v7NMdUrf

Elshan
  • 7,339
  • 4
  • 71
  • 106

3 Answers3

2

You have not made it clear that in your DataTable if you are looking for duplicates for any specific Item Code or for any Item Code. Anyways,here is the code for both the scenarios:-

If you are looking for duplicates for any specific Item Code then you can simply check the count like this:-

bool istxtGrdItmLocDuplicate = gridTable.AsEnumerable()
                        .Count(x => x.Field<string>("ItemCode") == txtGrdItmLoc.Text) > 1;

If you are looking for duplicates in the entire DataTable, then simply group by Item Code and check the respective count for each Item Code like this:-

bool isDuplicate = gridTable.AsEnumerable()
                            .GroupBy(x => x.Field<string>("ItemCode")
                            .Any(x => x.Count() > 1);
Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
  • 'EnumerableRowCollection' does not contain a definition for 'GroupBy' and no extension method 'GroupBy' accepting a first argument of type 'EnumerableRowCollection' could be found (are you missing a using directive or an assembly reference?) – GuidoG Sep 01 '17 at 15:28
  • @GuidoG - Have u added reference to _System.Linq_ ? I am sure you are missing that. – Rahul Singh Sep 04 '17 at 06:58
  • yes that was it. This happens so much they should fix it so it wont compile without that using and give a warning that you are missing a using... – GuidoG Sep 04 '17 at 07:11
  • @GuidoG - But Visual Studio add these namespaces by default ;) And it will give you suggestion if you press _Ctrl + . _ – Rahul Singh Sep 04 '17 at 08:20
  • I got VS 2015 pro and it never does that for me. Some setting maybe ? – GuidoG Sep 04 '17 at 09:23
0

First cast it to IEnumerable :

Convert DataRowCollection to IEnumerable<T>

Then you can use LINQ extension methods to do something like this (to check all values that has duplicates):

var duplicates = resultsList.Where(r => resultsList.Count(r2 => r2.Field<string>("Item Code") == r.Field<string>("Item Code")) > 0);

If you want check each value for duplicate you can use .Count method, something like this:

bool hasDuplicates = resultsList.Count(r2 => r2.Field<string>("Item Code") == "your code") > 1;

Ok, if for some reason this doesn't work you can write this function yourself:

public static class Helper
{
                                    // or other collection type
    public static int MyCount<T>(this IEnumerable<T> collection, Func<T, bool> function)
    {            
        int count = 0;
        foreach (T i in collection)
            if (function(i)) ++count;
        return count;
    }
}

And use it like :

results.MyCount(r => r.Field<string>("Item Code") == "Item Code");
Community
  • 1
  • 1
Fabjan
  • 13,506
  • 4
  • 25
  • 52
  • Error: System.Data.EnumerableRowCollection' does not contain a definition for 'Count' and no extension method 'Count' accepting a first argument of type.*What's you used .net framework version ?* – Elshan Aug 06 '15 at 06:39
  • That's odd, try to convert it with.ToList() method first... I'll update my answer... I used .Net 4.5 ... Updated my answer with .ToList() method – Fabjan Aug 06 '15 at 06:43
  • There's not method ToList() – Elshan Aug 06 '15 at 06:47
  • What version of .Net framework your project uses? `EnumerableRowCollection` class implements interface `IEnumerable` and this interface has lot's of extension methods from LINQ (like .Where .Count .ToList) that's why it **should** work... – Fabjan Aug 06 '15 at 06:50
  • Updated my answer with custom `Count()` method this should be enough to understand the general idea... – Fabjan Aug 06 '15 at 07:02
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/85272/discussion-between-jimmer-and-fabjan). – Elshan Aug 06 '15 at 07:12
0

IEnumerable<T> has a Count() method (check here), if you are not seeing it in intellisense then you are missing some using instruction, like using System.Linq; or some other...

Then you would just do:

if(results.Count()>0){
 //if there's duplicate row values 
 isNotDuplicate = false;
}
else
{
  isNotDuplicate=true;
}
Pinx0
  • 1,248
  • 17
  • 28
  • `EnumerableRowCollection` not contain method Count() – Elshan Aug 06 '15 at 07:11
  • `EnumerableRowCollection` implements `IEnumerable` so it MUST contain that method. I repeat, if you don't see it in intellisense, you are missing something, but it is there. – Pinx0 Aug 06 '15 at 07:21
  • Yes I dint's see it( Count() ) in intellisense.But there's no error. – Elshan Aug 06 '15 at 07:25