Linq query С# ASP.NET Core - linq

I'm executing a sql script using:
SqlCommand command = new SqlCommand(sqlQuery, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if(reader.HasRows)
{
while(reader.Read())
{
ViewModel vm = new ViewModel();
vm.Name = reader.GetString(1);
vm.Price = reader.GetDecimal(2);
vm.ReferenceNumber = reader.GetInt32(5);
returnList.Add(vm);
}
}
The above will produce result similar to this:
Name Price RefNumber
----------| --------|-----------
ABC | 93.45 | 1000
esd | 32.32 | 1002
def | 332.32 | 1000
In short, it's possible to have non-unique RefNumber so I want to disguise these number with a string. For example all refNumber with say:
1000 should be called to 'Ref 1' 1002 should be called to 'Ref 2' 1003 should be called to 'Ref 3 and so on.
How do I check this in the SqlDataReader to disguise the name and save to view model?
I've tried something like this:
if(reader.HasRows)
{
while(reader.Read())
{
ViewModel vm = new ViewModel();
vm.Name = reader.GetString(1);
vm.Price = reader.GetDecimal(2);
vm.ReferenceNumber = reader.GetInt32(5);
if(vm.ReferenceNumber == 1000)
{
vm.RefNameAsString = "Ref 1"
}
else if(vm.ReferenceNumber == 1002){
vm.RefNameAsString = "Ref 2"
}
else {
vm.RefNameAsString = "Ref 3"
}
returnList.Add(vm);
}
}
Something like that will produce the desire outcome but the problem is that the RefNumber may be long (100s) so I just want to put these as list and be able to change the name for each distinct reference number?
May be something like this:
foreach (var i in returnList.Select(x => x.ReferenceNumber).Distinct().ToList())
{
//how do I change the name for each unique value?
}

Assuming 1000 is always the base for the reference number, and it will never exceed 1999, then you could do something like:
var referenceNumberBase = 1000;
if(reader.HasRows)
{
while(reader.Read())
{
ViewModel vm = new ViewModel();
vm.Name = reader.GetString(1);
vm.Price = reader.GetDecimal(2);
vm.ReferenceNumber = reader.GetInt32(5);
if(vm.ReferenceNumber == referenceNumberBase)
vm.RefNameAsString = "Ref 1"
else
vm.RefNameAsString = $"Ref {vm.ReferenceNumber-referenceNumberBase}";
returnList.Add(vm);
}
}
Both 1000 and 1001 would generate "Ref 1", which might be a problem. If that's an issue, you could change 1000 to be "Ref 0" with just:
vm.RefNameAsString = $"Ref {vm.ReferenceNumber-referenceNumberBase}";
You can also try ignoring the first number for different bases, but there might be edge cases:
vm.RefNameAsString = $"Ref {Convert.ToInt32(vm.ReferenceNumber.ToString()[1..])};

Related

Union 2 lists with additional content change for ID that occurs in both source lists

How to merge these 2 collections?
Problem: When an ApplicationID is in listOfPM and listOfPM2, Test2 is null and should be a number
var listOfPM = from d in gbc
select new Tab24PresentationModel
{
ApplicationID = d.ApplicationID,
ApplicationName = d.ApplicationName,
Test1 = d.count,
Test2 = null
};
var listOfPM2 = from d in gbc2
select new Tab24PresentationModel
{
ApplicationID = d.ApplicationID,
ApplicationName = d.ApplicationName,
Test1 = null,
Test2 = d.count
};
var result = listOfPM.Union(listOfPM2);
Have tried removing the Test2 from list of PM and Test1 from listOfPM2 from each and get:
The type 'xxx.Tab24PresentationModel' appears in two structurally incompatible initializations within a single LINQ to Entities query. A type can be initialized in two places in the same query, but only if the same properties are set in both places and those properties are set in the same order.
I can think of ways around this using multiple foreach's.. would like to use Linq!
You need to merge the two objects (with same ApplicationID) manually, no way around that.
Edit - try this:
var list = gbc.Union( gbc2 ).ToLookup( d => d.ApplicationID ).Select( g =>
{
var first = g.First();
var retVal = new Tab24PresentationModel
{
ApplicationID = first.ApplicationID,
ApplicationName = first.ApplicationName,
Test1 = first.count,
Test2 = null
};
var second = g.Skip(1).Take(1).SingleOrDefault();
if( null != second )
{
retVal.Test2 = second.count;
}
return retVal;
} );
Edit 2: hrm, that would only work if you don't want Test1 = null, Test2 = value when only the gbc2 exists. If that's not an issue, you should be ok.
Many thanks for the answers and comments - here is what I came up with.
// take each list in turn and either add or update
var result = new List<Tab24PresentationModel>();
foreach (var t in listOfPM)
{
var a = new Tab24PresentationModel
{
ApplicationID = t.ApplicationID,
ApplicationName = t.ApplicationName,
Test1 = t.Test1
};
result.Add(a);
}
// list2
foreach (var t in listOfPM2)
{
// is this already in result
if (result.Any(x => x.ApplicationID == t.ApplicationID))
{
var existing = result.First(x => x.ApplicationID == t.ApplicationID);
existing.Test2 = t.Test2;
}
else
{
var a = new Tab24PresentationModel
{
ApplicationID = t.ApplicationID,
ApplicationName = t.ApplicationName,
Test2 = t.Test2
};
result.Add(a);
}
}

PIVOT with LINQ from Datatable [duplicate]

I have a collection of items that contain an Enum (TypeCode) and a User object, and I need to flatten it out to show in a grid. It's hard to explain, so let me show a quick example.
Collection has items like so:
TypeCode | User
---------------
1 | Don Smith
1 | Mike Jones
1 | James Ray
2 | Tom Rizzo
2 | Alex Homes
3 | Andy Bates
I need the output to be:
1 | 2 | 3
Don Smith | Tom Rizzo | Andy Bates
Mike Jones | Alex Homes |
James Ray | |
I've tried doing this using foreach, but I can't do it that way because I'd be inserting new items to the collection in the foreach, causing an error.
Can this be done in Linq in a cleaner fashion?
I'm not saying it is a great way to pivot - but it is a pivot...
// sample data
var data = new[] {
new { Foo = 1, Bar = "Don Smith"},
new { Foo = 1, Bar = "Mike Jones"},
new { Foo = 1, Bar = "James Ray"},
new { Foo = 2, Bar = "Tom Rizzo"},
new { Foo = 2, Bar = "Alex Homes"},
new { Foo = 3, Bar = "Andy Bates"},
};
// group into columns, and select the rows per column
var grps = from d in data
group d by d.Foo
into grp
select new {
Foo = grp.Key,
Bars = grp.Select(d2 => d2.Bar).ToArray()
};
// find the total number of (data) rows
int rows = grps.Max(grp => grp.Bars.Length);
// output columns
foreach (var grp in grps) {
Console.Write(grp.Foo + "\t");
}
Console.WriteLine();
// output data
for (int i = 0; i < rows; i++) {
foreach (var grp in grps) {
Console.Write((i < grp.Bars.Length ? grp.Bars[i] : null) + "\t");
}
Console.WriteLine();
}
Marc's answer gives sparse matrix that can't be pumped into Grid directly.
I tried to expand the code from the link provided by Vasu as below:
public static Dictionary<TKey1, Dictionary<TKey2, TValue>> Pivot3<TSource, TKey1, TKey2, TValue>(
this IEnumerable<TSource> source
, Func<TSource, TKey1> key1Selector
, Func<TSource, TKey2> key2Selector
, Func<IEnumerable<TSource>, TValue> aggregate)
{
return source.GroupBy(key1Selector).Select(
x => new
{
X = x.Key,
Y = source.GroupBy(key2Selector).Select(
z => new
{
Z = z.Key,
V = aggregate(from item in source
where key1Selector(item).Equals(x.Key)
&& key2Selector(item).Equals(z.Key)
select item
)
}
).ToDictionary(e => e.Z, o => o.V)
}
).ToDictionary(e => e.X, o => o.Y);
}
internal class Employee
{
public string Name { get; set; }
public string Department { get; set; }
public string Function { get; set; }
public decimal Salary { get; set; }
}
public void TestLinqExtenions()
{
var l = new List<Employee>() {
new Employee() { Name = "Fons", Department = "R&D", Function = "Trainer", Salary = 2000 },
new Employee() { Name = "Jim", Department = "R&D", Function = "Trainer", Salary = 3000 },
new Employee() { Name = "Ellen", Department = "Dev", Function = "Developer", Salary = 4000 },
new Employee() { Name = "Mike", Department = "Dev", Function = "Consultant", Salary = 5000 },
new Employee() { Name = "Jack", Department = "R&D", Function = "Developer", Salary = 6000 },
new Employee() { Name = "Demy", Department = "Dev", Function = "Consultant", Salary = 2000 }};
var result5 = l.Pivot3(emp => emp.Department, emp2 => emp2.Function, lst => lst.Sum(emp => emp.Salary));
var result6 = l.Pivot3(emp => emp.Function, emp2 => emp2.Department, lst => lst.Count());
}
* can't say anything about the performance though.
You can use Linq's .ToLookup to group in the manner you are looking for.
var lookup = data.ToLookup(d => d.TypeCode, d => d.User);
Then it's a matter of putting it into a form that your consumer can make sense of. For instance:
//Warning: untested code
var enumerators = lookup.Select(g => g.GetEnumerator()).ToList();
int columns = enumerators.Count;
while(columns > 0)
{
for(int i = 0; i < enumerators.Count; ++i)
{
var enumerator = enumerators[i];
if(enumator == null) continue;
if(!enumerator.MoveNext())
{
--columns;
enumerators[i] = null;
}
}
yield return enumerators.Select(e => (e != null) ? e.Current : null);
}
Put that in an IEnumerable<> method and it will (probably) return a collection (rows) of collections (column) of User where a null is put in a column that has no data.
I guess this is similar to Marc's answer, but I'll post it since I spent some time working on it. The results are separated by " | " as in your example. It also uses the IGrouping<int, string> type returned from the LINQ query when using a group by instead of constructing a new anonymous type. This is tested, working code.
var Items = new[] {
new { TypeCode = 1, UserName = "Don Smith"},
new { TypeCode = 1, UserName = "Mike Jones"},
new { TypeCode = 1, UserName = "James Ray"},
new { TypeCode = 2, UserName = "Tom Rizzo"},
new { TypeCode = 2, UserName = "Alex Homes"},
new { TypeCode = 3, UserName = "Andy Bates"}
};
var Columns = from i in Items
group i.UserName by i.TypeCode;
Dictionary<int, List<string>> Rows = new Dictionary<int, List<string>>();
int RowCount = Columns.Max(g => g.Count());
for (int i = 0; i <= RowCount; i++) // Row 0 is the header row.
{
Rows.Add(i, new List<string>());
}
int RowIndex;
foreach (IGrouping<int, string> c in Columns)
{
Rows[0].Add(c.Key.ToString());
RowIndex = 1;
foreach (string user in c)
{
Rows[RowIndex].Add(user);
RowIndex++;
}
for (int r = RowIndex; r <= Columns.Count(); r++)
{
Rows[r].Add(string.Empty);
}
}
foreach (List<string> row in Rows.Values)
{
Console.WriteLine(row.Aggregate((current, next) => current + " | " + next));
}
Console.ReadLine();
I also tested it with this input:
var Items = new[] {
new { TypeCode = 1, UserName = "Don Smith"},
new { TypeCode = 3, UserName = "Mike Jones"},
new { TypeCode = 3, UserName = "James Ray"},
new { TypeCode = 2, UserName = "Tom Rizzo"},
new { TypeCode = 2, UserName = "Alex Homes"},
new { TypeCode = 3, UserName = "Andy Bates"}
};
Which produced the following results showing that the first column doesn't need to contain the longest list. You could use OrderBy to get the columns ordered by TypeCode if needed.
1 | 3 | 2
Don Smith | Mike Jones | Tom Rizzo
| James Ray | Alex Homes
| Andy Bates |
#Sanjaya.Tio I was intrigued by your answer and created this adaptation which minimizes keySelector execution. (untested)
public static Dictionary<TKey1, Dictionary<TKey2, TValue>> Pivot3<TSource, TKey1, TKey2, TValue>(
this IEnumerable<TSource> source
, Func<TSource, TKey1> key1Selector
, Func<TSource, TKey2> key2Selector
, Func<IEnumerable<TSource>, TValue> aggregate)
{
var lookup = source.ToLookup(x => new {Key1 = key1Selector(x), Key2 = key2Selector(x)});
List<TKey1> key1s = lookup.Select(g => g.Key.Key1).Distinct().ToList();
List<TKey2> key2s = lookup.Select(g => g.Key.Key2).Distinct().ToList();
var resultQuery =
from key1 in key1s
from key2 in key2s
let lookupKey = new {Key1 = key1, Key2 = key2}
let g = lookup[lookupKey]
let resultValue = g.Any() ? aggregate(g) : default(TValue)
select new {Key1 = key1, Key2 = key2, ResultValue = resultValue};
Dictionary<TKey1, Dictionary<TKey2, TValue>> result = new Dictionary<TKey1, Dictionary<TKey2, TValue>>();
foreach(var resultItem in resultQuery)
{
TKey1 key1 = resultItem.Key1;
TKey2 key2 = resultItem.Key2;
TValue resultValue = resultItem.ResultValue;
if (!result.ContainsKey(key1))
{
result[key1] = new Dictionary<TKey2, TValue>();
}
var subDictionary = result[key1];
subDictionary[key2] = resultValue;
}
return result;
}

Referencing the collection your working on within LINQ

I am working with linq, and im wondering if there is any way that I might reference the collection I am working on from within my linq code? What I am looking for is something like this:
let result = (from t in someCollection
where t == something
select t).Where(res => res.start == THIS.Min(temp => temp.start))
So what I want to achieve in this query is that the THIS variable should provide a reference to the collection that the where clause is being applied to:
(from t in someCollection
where t == something
select t)
There are lots of ways to get around this problem, but I am specifically interested in a way of using a reference to the collection in use. Hope some of you know something about this!
Thanks!
The way to do what your example states is like this:
var minValue = someCollection.Min(x => x.start);
var result = from t in someCollection
where t.id > 5 // replace this line with your "where t == something"
where t.start == minValue
select t;
but say that you have to do some kind of other comparison for every
element in your collection to every other element. Is some there some
way of doing a thing like this?
If you really need to compare one item with every other item in the list, you could pattern your code like this:
var result = from t in someCollection
where t.id > 5 // replace this line with your "where t == something"
let minValue = someCollection.Min (x => x.start)
where t.start == minValue
select t;
The problem with the second example is that every item you visit in your someCollection it will be forced to recalculate the minValue.
Now, here's a completely contrived example that illustrates having to access the entire collection while accessing each member of the collection. It simply goes through a list of items and outputs each item along with all the other items that have lesser dates:
var eventItems = new[]
{
new { Name = "alpha", DateCreated = DateTime.Today.AddDays(1) },
new { Name = "bravo", DateCreated = DateTime.Today.AddDays(2) },
new { Name = "charlie", DateCreated = DateTime.Today.AddDays(-1) },
new { Name = "delta", DateCreated = DateTime.Today.AddDays(-5) },
new { Name = "echo", DateCreated = DateTime.Today.AddDays(-3) },
new { Name = "foxtrot", DateCreated = DateTime.Today.AddDays(3) },
new { Name = "golf", DateCreated = DateTime.Today.AddDays(-4) }
};
var results = from item in eventItems
where item.Name.Length > 2
let prevDays = eventItems.Where (i => i.DateCreated < item.DateCreated)
select new
{
Name = item.Name,
CurrentDate = item.DateCreated,
PreviousItems = prevDays
};
The output:
Perhaps one of these examples will help you with your exact problem.

Dynamic Linq to Datatable Derived Field

Is it possible to use Dynamic Linq to run a query similar to:
Select a, b, a + b as c
from MyDataTable
I have an application where the user can enter SQL statements, the results of these statements are then assigned to a DataTable. There is also the option to derive a field based on other fields. (e.g. user can say field C = a + b, or field D = A*B+10 etc).
Ideally I would like to do something similar to:
string myCalc = "Convert.ToDouble(r.ItemArray[14])+Convert.ToDouble(r.ItemArray[45])";
var parameters = from r in dt.AsEnumerable()
select (myCalc);
What I want to do in this example is add the value of column 14 to column 45 and return it. It's up to the user to decide what expression to use so the text in the select needs to be from a string, I cannot hard code the expression. The string myCalc is purely for demonstration purposes.
You could do that using a Dictionary, and a DataReader and Dynamic Queries. Here is an example based in part in Rob Connery's Massive ORM RecordToExpando:
void Main()
{
string connString = "your connection string";
System.Data.SqlClient.SqlConnection conn = new SqlConnection(connString);
string statement = "SUM = EstimatedEffort + OriginalEstimate, Original = OriginalEstimate";
// Note: You should parse the statement so it doesn't have any updates or inserts in it.
string sql = "SELECT " + statement +" FROM Activities";
List<IDictionary<string, object>> results = new List<IDictionary<string, object>>();
conn.Open();
using(conn)
{
var cmd = new SqlCommand(sql, conn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var dic = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
dic.Add(
reader.GetName(i),
DBNull.Value.Equals(reader[i]) ? null : reader[i]);
}
results.Add(dic);
}
}
foreach (var dicRow in results)
{
foreach (string key in dicRow.Keys)
{
Console.Write("Key: " + key + " Value: " + dicRow[key]);
}
Console.WriteLine();
}
}
Something like this:
void Main()
{
var dataTable = new DataTable();
dataTable.Columns.Add("a", typeof(double));
dataTable.Columns.Add("b", typeof(double));
dataTable.Rows.Add(new object[] { 10, 20 });
dataTable.Rows.Add(new object[] { 30, 40 });
string myCalc = "Convert.ToDouble(ItemArray[0]) + Convert.ToDouble(ItemArray[1])";
var query = dataTable.AsEnumerable().AsQueryable();
var result = query.Select(myCalc);
foreach (Double c in result)
{
System.Console.WriteLine(c);
}
}

Use LINQ to concatenate multiple rows into single row (CSV property)

I'm looking for the LINQ equivalent to the Sybase's LIST() or MySQL's group_concat()
It'll convert:
User Hobby
--------------
Bob Football
Bob Golf
Bob Tennis
Sue Sleeping
Sue Drinking
To:
User Hobby
--------------
Bob Football, Golf, Tennis
Sue Sleeping, Drinking
That's the GroupBy operator. Are you using LINQ to Objects?
Here's an example:
using System;
using System.Collections.Generic;
using System.Linq;
public class Test
{
static void Main()
{
var users = new[]
{
new { User="Bob", Hobby="Football" },
new { User="Bob", Hobby="Golf" },
new { User="Bob", Hobby="Tennis" },
new { User="Sue", Hobby="Sleeping" },
new { User="Sue", Hobby="Drinking" },
};
var groupedUsers = users.GroupBy(user => user.User);
foreach (var group in groupedUsers)
{
Console.WriteLine("{0}: ", group.Key);
foreach (var entry in group)
{
Console.WriteLine(" {0}", entry.Hobby);
}
}
}
}
That does the grouping - can you manage the rest yourself?
See if this solution helps you:
List<User> users = new List<User>()
{
new User {Name = "Bob", Hobby = "Football" },
new User {Name = "Bob", Hobby = "Golf"},
new User {Name = "Bob", Hobby = "Tennis"},
new User {Name = "Sue", Hobby = "Sleeping"},
new User {Name = "Sue", Hobby = "Drinking"}
};
var groupedUsers = from u in users
group u by u.Name into g
select new
{
Name = g.First<User>().Name,
Hobby = g.Select(u => u.Hobby)
};
foreach (var user in groupedUsers)
{
Console.WriteLine("Name: {0}", user.Name);
foreach (var hobby in user.Hobby)
{
Console.WriteLine("Hobby: {0}", hobby);
}
}
re the _concat aspect of your question, using:
static class EnumerableExtensions
{
public static String AsJoined( this IEnumerable<String> enumerable )
{
return AsJoined( enumerable, "," );
}
public static String AsJoined( this IEnumerable<String> enumerable, String separator )
{
return String.Join( separator, enumerable.ToArray() );
}
}
The outputting foreach in bruno conde and Jon Skeet's answers can become:
Console.WriteLine( "User:\tHobbies");
foreach ( var group in groupedUsers )
Console.WriteLine( "{0}:\t{1}", group.Key, group.Select( g => g.Hobby ).AsJoined( ", " ) );
... and you'll get the precise result output format you asked for (yes, I know the others have already solved your problem, but its hard to resist!)
Or else we can do the following-
var users = new[]
{
new { User="Bob", Hobby="Football" },
new { User="Bob", Hobby="Golf" },
new { User="Bob", Hobby="Tennis" },
new { User="Sue", Hobby="Sleeping" },
new { User="Sue", Hobby="Drinking" },
};
var userList = users.ToList();
var ug = (from user in users
group user by user.User into groupedUserList
select new { user = groupedUserList.Key, hobby = groupedUserList.Select(g =>g.Hobby)});
var ug2 = (from groupeduser in ug
select new{ groupeduser.user, hobby =string.Join(",", groupeduser.hobby)});
To do it in one Linq Statement. There is no way I'd recommend the code, but it shows that it could be done.
var groupedUsers = from user in users
group user by user.User into userGroup
select new
{
User = userGroup.Key,
userHobies =
userGroup.Aggregate((a, b) =>
new { User = a.User, Hobby = (a.Hobby + ", " + b.Hobby) }).Hobby
}
;
foreach (var x in groupedUsers)
{
Debug.WriteLine(String.Format("{0} {1}", x.User, x.userHobies));
}
all answers is not good enough;
because this is a db query,but all of us do that just in memory;
diff is that some operation in memory will occuce a error can't trans to store expression;
var list = db.Users.GroupBy(s=>s.User).
select(g=>new{user=g.Key,hobbys=g.select(s=>s.Hobby)}); // you can just do that from db
var result=list.ToList(); // this is important,to query data to memory;
var result2 = result.select(g=>new{user=g.Key,hobbyes=string.join(",",g.hobbyes)}; //then,do what you love in memory

Resources