Linq - multiple rows as string - asp.net-mvc-3

Lets assume that I have Table which contains Username and the other one which contains FirstName. A single user can have multiple FirstNames:
How can I obtain a record which will contain Username and all first names separated by comma?
i. e.
Users
id | Username
1 | Test
Names
UserId | FirstName
1 | Mike
1 | John
I would like to receive a record which will contain
Test, "Mike, John"
How can I do that?
Edit: What if Users table will have more columns which I want to get?
i. e.
id | Username | Status
1 | Test | Active
How to get Test, Active, "Mike, John"?

You can use GroupBy and String.Join
var userGroups = from u in users
join n in names
on u.ID equals n.UserID
group new{n, u} by n.UserID into UserGrp
select new
{
Username = UserGrp.Key,
Status = UserGrp.First().u.Status,
Names = string.Join(",", UserGrp.Select(x => x.n.Name))
};
foreach (var ug in userGroups)
Console.WriteLine("{0}, {1}, \"{2}\"", ug.Username, ug.Status, ug.Names);

Related

Scanning into struct of gorm query

I'm trying to scan the result of a query into a res structure.
The code builds and the query passes but the result array consists of default values like this:
[{0 0 0} {0 0 0} {0 0 0} {0 0 0} {0 0 0} {0 0 0}]
Also, result array has the exact length as the query result should have.
When i try generated query in postgres shell it returns the result correctly.
Code:
type res struct{
id int
number int
user_id int
}
func getDataJoin(){
new := []res{}
db.Db.Table("users").Select("users.id as id, credit_cards.number as number, credit_cards.user_id as user_id").Joins("left join credit_cards on credit_cards.user_id = users.id").Scan(&new)
fmt.Println("user\n",new)
}
Generated Query:
SELECT users.id as id, credit_cards.number as number, credit_cards.user_id as user_id FROM "users" left join credit_cards on credit_cards.user_id = users.id
Database result
id | number | user_id
----+--------+---------
1 | 1 | 1
1 | 2 | 1
2 | 1 | 2
2 | 2 | 2
3 | 1 | 3
3 | 2 | 3
(6 rows)
Since go-gorm has a certain convention when it comes to naming, you might want to try two things.
Make your res struct publicly available, with public fields:
type Res struct{
ID int
Number int
UserID int
}
Or, specify mappings between columns and fields:
type res struct{
id int `gorm:"column:id"`
number int `gorm:"column:number"`
user_id int `gorm:"column:user_id"`
}
gorm can only read/write on exported fields much like Marshal/Unmarshal methods of json package. If the first letter of your field is in capital, it will be used. By default, gorm matches struct fields with their camel-cased forms. You can also define your own column names.
Since camel-cased form of both ID and Id, is id, as long as the first letter of your field is in capital, it should work. On a different note, it's good practice to write ID, i.e., both letter capital.

spring data exists by all values of some column

I want to know, is there set of entities by following rule:
I have a table with two primary keys:
| id | key |
| 1 | a |
| 2 | b |
| 1 | c |
So, I want to do something like that:
boolean existsByIdAndAllOfKey(
long id,
Set<Key> keys
)
This query should return true if in the database there are entities with all keys presented in input Set.
I wondering is there any keyword from spring data? Or what is the best way to do that?
found following solution:
int countByIdAndKeyIn(
long id,
Set<Key> keys
)
boolean isThereEntityWithAllKeys(long id, Set<Key> keys) {
return countByIdAndKeyIn(id, keys) == keys.size;
}

Implementing tables in lua to access specific pieces for later use

I am trying to make a table store 3 parts which will each be huge in length. The first is the name, second is EID, third is SID. I want to be able to get the information like this name[1] gives me the first name in the list of names, and like so for the other two. I'm running into problems with how to do this because it seems like everyone has their own way which are all very very different from one another. right now this is what I have.
info = {
{name = "btest", EID = "19867", SID = "664"},
{name = "btest1", EID = "19867", SID = "664"},
{name = "btest2", EID = "19867", SID = "664"},
{name = "btest3", EID = "19867", SID = "664"},
}
Theoretically speaking would i be able to just say info.name[1]? Or how else would I be able to arrange the table so I can access each part separately?
There are two main "ways" of storing the data:
Horizontal partitioning (Object-oriented)
Store each row of the data in a table. All tables must have the same fields.
Advantages: Each table contains related data, so it's easier passing it around (e.g, f(info[5])).
Disadvantages: A table is to be created for each element, adding some overhead.
This looks exactly like your example:
info = {
{name = "btest", EID = "19867", SID = "664"},
-- etc ...
}
print(info[2].names) -- access second name
Vertical partioning (Array-oriented)
Store each property in a table. All tables must have the same length.
Advantages: Less tables overall, and slightly more time and space efficient (Lua VM uses actual arrays).
Disadvantages: Needs two objects to refer to a row: the table and the index. It's harder to insert/delete.
Your example would look like this:
info = {
names = { "btest", "btest1", "btest2", "btest3", },
EID = { "19867", "19867", "19867", "19867", },
SID = { "664", "664", "664", "664", },
}
print(info.names[2]) -- access second name
So which one should I choose?
Unless you are really need performance, you should go with horizontal partitioning. It's far more common working over full rows, and gives you more freedom in how you use your structures. If you decide to go full OO, having your data in horizontal form will be much easier.
Addendum
The names "horizontal" and "vertical" come from the table representation of a relational database.
| names | EID | SID | | names |
--+-------+-----+-----+ +-------+
1 | | | | | | --+-------+-----+-----+
2 | | | | | | 2 | | | |
3 | | | | | | --+-------+-----+-----+
Your info table is an array, so you can access items using info[N] where N is any number from 1 to the number of items in the table. Each field of the info table is itself a table. The 2nd item of info is info[2], so the name field of that item is info[2].name.

Generate json result based on two related entites

I have two related one to many entities
Race and Cars (on race contains a lot of cars)
I need to generate an json result to pass it to jQGrid, i thought may be it is possible to do that without creating new class witch would contain properties. I thought I can go like that:
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (from c in Races
select new
{
//c.Cars.Id.ToString(), - need iteration
cell = new string[] {
//c.Cars.Id.ToString(), - need iteration
c.Date.ToString(),
c.Type.ToString(),
c.Cars //But how i may loop all Cars colection here?
//c.Cars.Name - need iteration
//c.Cars.Speed - need iteration
}
}).ToArray()
};
But the Cars property represent collection. How may i iterate that inside collection initializer? Or should i better create class witch would contain all the properties i need?
Any ideas?
Lets say Car has properties Name Speed Id and Race has properties Date, Type
The data will be displayed like that:
Date | Type | Id | Name | Speed
02/03/2011 | A | 1 | MegaName1 | 130
02/03/2011 | A | 2 | MegaName2 | 112
02/03/2011 | A | 3 | MegaName3 | 132
03/05/2011 | B | 4 | MegaName2 | 112
03/05/2011 | B | 5 | MegaName4 | 33
Try the following:
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows =
(from race in races
from car in race.Cars
select new
{
cell = new string[]
{
race.Date.ToString(),
race.Type,
car.Id,
car.Name,
car.Speed.ToString()
}
}).ToArray()
};

Read Excel using LINQ

I want to read excel 2003( cannot change as its coming from third party) and group data in List or Dictionary (I don't which one is good)
for example below (Excel formatting )
Books Data [first row and first column in excel]
second row( no records)
Code,Name,IBN [third row (second column, third column]
Aust [fourth row, first column]
UX test1 34 [ fifth row (second column, third column]
......
....
Books Data
Code Name IBN
Aust
UX test1 34
UZ test2 345
UN test3 5654
US
UX name1 567
TG nam2 123
UM name3 234
I am reading excel data using following code( some help from Google)
string filename = #"C:\\" + "Book1.xls";
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + filename + ";" +
"Extended Properties=Excel 8.0;";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString);
DataSet myDataSet = new DataSet();
dataAdapter.Fill(myDataSet, "BookInfo");
DataTable dataTable = myDataSet.Tables["BookInfo"];
var rows = from p in dataTable.AsEnumerable()
where p[0].ToString() != null || p[0].ToString() != "" && p.Field<string>("F2") != null
select new
{ countryName= p[0],
bookCode= p.Field<string>("F2"),
bookName= p.Field<string>("F3")
};
The code above is not good as to get the “Code” I am using “ F2” and for country I am using p[0].What should I use to get the code and name for each country.
Also it’s give the information I want but I don't how to put in list or dictionary or in class so I can get data by passing parameter as a country name.
In short first it must put all data in list or dictionary and then you can call list or dictionary get data filter by country.
Thanks
There's two things you need to do:
First, you need to reformat the spreadsheet to have the column headers on the first row like the table below shows
| Country | Code | Name | IBN |
|---------|------|---------|------|
| Aust | UX | test1 | 34 |
| Aust | UZ | test2 | 345 |
| Aust | UN | test3 | 5654 |
| US | UX | name1 | 567 |
| US | TG | name2 | 123 |
| US | UM | name3 | 234 |
Second, use the Linq to Excel library to retrieve the data. It takes care of making the oledb connection and creating the sql for you. Below is an example of how easy it is to use the library
var book = new ExcelQueryFactory("pathToExcelFile");
var australia = from x in book.Worksheet()
where x["Country"] == "Aust"
select new
{
Country = x["Country"],
BookCode = x["Code"],
BookName = x["Name"]
};
Checkout the Linq to Excel intro video for more information about the open source project.
Suggestion 1
Checkout THIS link......as AKofC suggests, creating a class to hold your data would be your first port of call. The link I have posted has a small example of the sort of idea we are proposing.
Suggestion 2 with example...
The obvious thing to do from the code you have posted would be to create a new class to store your book information in.
Then you simply define which fields from your excel document it is that you want to pass into the new instance of your bookinformation class.
New Book Information Class:
class MyBookInfo
{
public string CountryName { get; set; }
public string BookCode { get; set; }
public string BookName { get; set; }
}
Method To Retrieve Info:
public void GetMyBookInfoFromExcelDocument()
{
string filename = #"C:\\" + "Book1.xls";
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + filename + ";" +
"Extended Properties=Excel 8.0;";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString);
DataSet myDataSet = new DataSet();
dataAdapter.Fill(myDataSet, "BookInfo");
DataTable dataTable = myDataSet.Tables["BookInfo"];
var rows = from p in dataTable.AsEnumerable()
where p[0].ToString() != null || p[0].ToString() != "" && p.Field<string>("F2") != null
select new MyBookInfo
{
CountryName = p.Field<string>("InsertFieldNameHere"),
BookCode = p.Field<string>("InsertFieldNameHere"),
BookName = p.Field<string>("InsertFieldNameHere")
};
}
From what I understand, I suggest creating a BookData class containing the properties you need, in this case Country, Code, Name, and IBN.
Then once you've filled your DataSet with the Excel stuff, create a new List, and loop through the DataRows in the DataSet adding the Excel values to the List.
Then you can use Linq on the List like so:
List<BookData> results = from books in bookList
where books.country == 'US'
select books;
Or something like that. I don't have Visual Studio on me, and Intellisense has spoiled me, so yeah. >__>

Resources