Find distinct values from column of datatable in c# and store distinct values in variables - c#-4.0

i want to find distinct values from a column of datatable in c# and also want to store all these distinct values in variables
DataTable dtable = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * from clubbb ", con);
da.Fill(dtable, "clubbb");
int toto = bdtable.AsEnumerable().Distinct().Count();

You need to implement the interface IEqualityComparer<DataRow> methods to provide the way the Distinct method will use to know whether 2 rows are duplicate or not. This can be achieved with a class like this:
public class CustomComparer : IEqualityComparer<DataRow>
{
public bool Equals(DataRow x, DataRow y)
{
// your custom equality logic here
}
public int GetHashCode(DataRow obj)
{
// return hash code depending on your distinct criteria
}
}
Then change the call you made:
int toto = bdtable.AsEnumerable().Distinct(new CustomComparer()).Count();
I had similar problem, and in my case I needed to know distinct values of specific column, so I passed the name of this column to the custom comparer I implemented, so that GetHashCode will return identical hash codes for duplicate values.
You can read more here: https://msdn.microsoft.com/en-us/library/ms132151(v=vs.110).aspx
Hope this helps :)

Related

JOOQ: fetchGroups() always returns list with only one element

I'm new to JOOQ and currently fail to map a joined query to Map<K, List<V>>: the list always only contains one element.
Here's my code:
DSL.using(...)
.select(ORDER.fields())
.select(ORDER_ITEM_ARTICLE.fields())
.from(ORDER)
.leftOuterJoin(ORDER_ITEM_ARTICLE).on(ORDER.ID.eq(ORDER_ITEM_ARTICLE.ORDER_ID))
// to Map<InOutOrder, List<OrderItemArticle>>
.fetchGroups(
r -> r.into(ORDER).into(InOutOrder.class),
r -> r.into(ORDER_ITEM_ARTICLE).into(OrderItemArticle.class)
)
// map to InOutOrder
.entrySet().stream().map( e -> {
// e.getValue() always returns list with only 1 element?!
e.getKey().articles = e.getValue();
return e.getKey();
})
.collect(Collectors.toList())
;
Say I have 1 row in ORDER and 2 corresponding rows in ORDER_ITEM_ARTICLE. Running the SQL returned by .getSQL() (after .fetchGroups()), returns me 2 rows as expected, so I assumed the fetchGroups() call will populate my list with two entries as well?!
What am I missing?
Thanks!
Update:
As requested, the InOutOrder class:
public class InOutOrder extends Order {
public List<OrderItemArticle> articles;
public List<OrderItemOther> others;
public List<OrderItemCost> costs;
public List<OrderContact> contacts;
public List<EmailJob> emailJobs;
}
So this is just an extension of the JOOQ POJO class and is used for JSON communication with the API clients...
fetchGroups() simply puts objects in a LinkedHashMap. You have to adhere to the usual Map contract, which means implementing equals() and hashCode(). Without it, each object you're creating (or which jOOQ is creating for you) will use identity comparison, so you get every "value" only once in the result.

Get Column Names in HBase Thrift C++?

I need to get the list of column qualifiers available in a HBase table.
Suppose I have a table 'Customers' with column 'info:Age' and 'contact:PhoneNo'. To get the list of column families I see there's a method 'getColumnDescriptors' which returns the value 'info' and 'contact'.
But how to retrieve the full column names 'info:Age' and 'contact:PhoneNo' from the table or atleast the qualifiers 'Age' and 'PhoneNo' alone.
With the method 'getRowWithColumns' I am able to get the list of column names where I have to pass the row key value.
Will I be able to achieve this through any other convenient way?
Here is a working solution in Java as you asked, you just have to change a few things to translate it to C++.
Basically this method will scan the table and retrieves the column qualifiers, then I add them into a list if this list does not already contains it.
Here, I look at all the rows, but if all your rows always have the same columns, you can just scan the first row, using a Get for example (look at the HBase documentation, I've written several examples there).
public ArrayList<String> getColumnName(String tablename) {
ArrayList<String> properties = new ArrayList<String>();
try {
Table table = this.connection.getTable(TableName.valueOf(tablename));
Scan scan = new Scan();
ResultScanner rs = table.getScanner(scan);
try {
for (Result r = rs.next(); r != null; r = rs.next()) {
for (Cell c : r.rawCells()) {
String family = new String(CellUtil.cloneFamily(c));
String qualifier = new String(CellUtil.cloneQualifier(c));
System.out.println("Column Family : "+ family);
System.out.println("Column Qualifier : " + qualifier);
if (!properties.contains(qualifier))
properties.add(new String(CellUtil.cloneQualifier(c)));
}
}
} finally {
rs.close(); // always close the ResultScanner!
}
} catch (IOException e) {
e.printStackTrace();
}
return properties;
}

How to search and sort in J2me (ascending or descending)

I am wondering about how to search in J2ME. I have been searching in the internet, so many result show to me, and I see in Java2s.com I got a result use RecordFilter and matches method for search in record store.
But my problem is, when I need to pass 2 or more parameters into it. How can result matches with these parameter?
And how to sort descending or ascending like bubble sort?
Concatenate your searches into a single String variable. Separate each of them with ; for example. In the code of the matches method explode the String to get each search criteria.
To make the filter in effect create an instance of SearchFilter and call the matches method with the concantenated String as its param.
For the sort implement the RecordComparator interface ; implement the compare method to build your sort criteria. Make a google search about j2me+recordcomparator to see examples about how to make sorts.
EDIT :
In the code of the matches method explode the String param obtained from the byte[] param. Treat each String exploded to make the criteria.
As I understand you want to pass two string as a search criteria when you wrote :
SearchFilter search = new SearchFilter(txtSearch.getString(), strType);
So in the constructor there should be two params !!!
When you want to make the matching then call
if searchFilter.matches((search1+";"+sType).getBytes())
Then explode the candidate param into two String when you code the matches method.
When I save my Data in RMS I save it as a String[] like I want to save Name, Age,Salary,EmpID for each employee I save it create an array and convert it to bytes and save it in RMS. When i retrieve it i do the reverse process. Now if i want to get employee with names starting with A and with salary 10000 i use the following filter
class UtilFilter implements RecordFilter{
public UtilFilter(String str_searchText,String str_searchText1)
{
this.str_searchText = str_searchText.toLowerCase();
this.str_searchText1 = str_searchText1.toLowerCase();
}
public boolean matches(byte[] bt_byteData)
{
String str_str = "";
String str_str1 = "";
//here goes code how u get back ur String[] from RMS say u get it in Data
str_str = Data[0].trim();
str_str1 = gd_cd.Data[2].trim();
if(str_searchText != null && str_searchText1 != null && str_str.equals(str_searchText) && str_str1.equals(str_searchText1 ))
{
return true;
}
else
{
return false;
}
}
}
This way i can filter any no of parameters.Hope tht helps! :)

How to assign all matching properties from Groovy object to Java object?

I want to use Groovy with JDBC to load some data from a table. I then want to copy the properties across where the property names match. How can I do this in Groovy?
Something like this:
sql.eachRow("select * from temp_table") {
def e = new MyJavaClass()
// copy matching fields from it to e
}
In addition to topchef's answer, you might be able to use some groovy map magic
If you limit your sql to the properties in your Java Class (and assuming you can hold the entire result in memory at once), then you should be able to use the rows method to get a List of GroovyRowResult objects (one per row). As this class is an instance of Map, groovy will use it to construct your java object automatically for you:
class MyJavaClass {
String property1, property2, property3
}
sql.rows("select property1, property2, property3 from temp_table").each { row ->
MyJavaClass e = row
}
Some groovy magic helps:
def filtered = ['property1', 'property2', ....]
sql.eachRow("select * from temp_table") {
def e = new MyJavaClass(it.properties.findAll{filtered.contains(it.key)})
}
Given that
list filtered contains all property names that you intend to copy;
your table column names correspond to MyJavaClass declared property names (the same as in the list filtered);
MyJavaClass has both default (empty) constructor and constructor
that takes all properties as parameters;
MyJavaClass declares public setters for properties;
E.g:
public MyJavaClass() {}
public MyJavaClass(String property1, String property2, ....) {
this.property1 = property1;
this.property2 = property2;
.... }
public void setProperty1(String property1) {this.property1 = property1;}
public void setProperty2(String property2) {this.property2 = property2;}
....
You may use filtered as a list of undesired properties like this:
def filtered = ['class', 'metaClass', ....]
then:
def e = new MyJavaClass(it.properties.findAll{!filtered.contains(it.key)})

Dynamic Object C# 4.0 , Creating columns at runtime from Pre-defined values

I have used dynamic object but here is a situation where the column names comes from a pre-defined string arrays.How can i create objects at runtime with these pre-defined set of column values?.
The reason why i wanted to do this way is to create a custom class and add custom validation attributes in it so that i can use reflection at runtime to populate values to these dynamic objects mapped to my custom class and validate the values using a single function.
dynamic x = new MyCustomClass();
x.Name = "Jones"; // The Field or Column name "Name" comes from a array of strings.
Validator.Validate(x); //Here i use reflection to iterate through the custom attributes on MyCustomClass and validate them based on conditions.
Is it possible to do something like this x."Name" = "Jones"; :-)
I would suggest perhaps adding an indexer property to your MyCustomClass?
public string this[string binder] {
get {
string result;
return (this.TryGetMember(binder, out result)) ? result : string.Empty
}
set {
this.TrySetMember(binder, value);
}
}
x["Name"] = "Jones";

Resources