How to include null vlaues while sorting using linq - c#

I am having 2 reports and combining them into a list. some of the item has null values.when i do sorting, it moves null values at the last.
Here is the sample program
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Report> reports = new List<Report>();
Report[] report1 = {
new Report{Id=10001,Date=null},
new Report{Id=10001,Date=null},
new Report{Id=10001,Date=Convert.ToDateTime("01/01/2017")}};
Report[] report2 = {
new Report{Id=10002,Date=null},
new Report{Id=10002,Date=null},
new Report{Id=10002,Date=Convert.ToDateTime("03/01/2017")}};
Report[] report3 = {
new Report{Id=10003,Date=null},
new Report{Id=10003,Date=null},
new Report{Id=10003,Date=Convert.ToDateTime("05/01/2017")}};
Report[] report4 = {
new Report{Id=10004,Date=null},
new Report{Id=10004,Date=null},
new Report{Id=10004,Date=Convert.ToDateTime("07/01/2017")}};
reports.AddRange(report1);
reports.AddRange(report2);
reports.AddRange(report3);
reports.AddRange(report4);
var report5 = new List<Report>()
{
new Report{Id=null,Date=Convert.ToDateTime("02/01/2017")},
new Report{Id=null,Date=Convert.ToDateTime("04/01/2017")},
new Report{Id=null,Date=Convert.ToDateTime("06/01/2017")},
};
reports.AddRange(report5);
foreach (var report in reports.OrderByDescending(x => x.Date))
{
Console.WriteLine("ID = " + report.Id + " " + "Date = " + report.Date);
}
Console.ReadKey();
}
}
class Report
{
public int? Id { get; set; }
public DateTime? Date { get; set; }
}
}
Sorting should be made based on the date and should not skip/move the null values of report list. Output should be as follows.
ID = 10004 Date =
ID = 10004 Date =
ID = 10004 Date = 07/01/2017
ID = Date = 06/01/2017
ID = 10003 Date =
ID = 10003 Date =
ID = 10003 Date = 05/01/2017
ID = Date = 04/01/2017
ID = 10002 Date =
ID = 10002 Date =
ID = 10002 Date = 03/01/2017
ID = Date = 02/01/2017
ID = 10001 Date =
ID = 10001 Date =
ID = 10001 Date = 01/01/2017

So, if I understood your answer correctly, you want to order by the ID's of the reports, and then the dates.
Change this:
foreach (var report in reports.OrderByDescending(x => x.Date))
{
Console.WriteLine("ID = " + report.Id + " " + "Date = " + report.Date);
}
to this:
foreach (var report in reports.OrderByDescending(x => x.Id).ThenBy(x => x.Date))
{
Console.WriteLine("ID = " + report.Id + " " + "Date = " + report.Date);
}
The latter sorts the reports by their ID, then by their date.

If I understood correctly, you want to order by Date first, and if Date is null, use ID for ordering. In this case, you need custom Report comparer.
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Report> reports = new List<Report>();
Report[] report1 =
{
new Report {Id = 10001, Date = null},
new Report {Id = 10001, Date = null},
new Report {Id = 10001, Date = Convert.ToDateTime("01/01/2017")}
};
Report[] report2 =
{
new Report {Id = 10002, Date = null},
new Report {Id = 10002, Date = null},
new Report {Id = 10002, Date = Convert.ToDateTime("03/01/2017")}
};
Report[] report3 =
{
new Report {Id = 10003, Date = null},
new Report {Id = 10003, Date = null},
new Report {Id = 10003, Date = Convert.ToDateTime("05/01/2017")}
};
Report[] report4 =
{
new Report {Id = 10004, Date = null},
new Report {Id = 10004, Date = null},
new Report {Id = 10004, Date = Convert.ToDateTime("07/01/2017")}
};
reports.AddRange(report1);
reports.AddRange(report2);
reports.AddRange(report3);
reports.AddRange(report4);
var report5 = new List<Report>()
{
new Report {Id = null, Date = Convert.ToDateTime("02/01/2017")},
new Report {Id = null, Date = Convert.ToDateTime("04/01/2017")},
new Report {Id = null, Date = Convert.ToDateTime("06/01/2017")},
};
reports.AddRange(report5);
foreach (var report in reports.OrderByDescending(x => x, new ReportComparer()))
{
Console.WriteLine("ID = " + report.Id + " " + "Date = " + report.Date);
}
Console.ReadKey();
}
class ReportComparer: IComparer<Report>
{
public int Compare(Report x, Report y)
{
// write your ordering rules here
if (x.Date.HasValue && y.Date.HasValue)
{
return x.Date.Value.CompareTo(y.Date.Value);
}
return x.Id.Value.CompareTo(y.Id.Value);
}
}
class Report
{
public int? Id { get; set; }
public DateTime? Date { get; set; }
}
}
}

I would recommend not using linq for this.
I would create your own sort function.
Something like a bubble sort simple bubble sort
Where you can change the condition for swapping the elements.

You can do as assign you null Date with DateTime.MaxValue then order your list and reassign DateTime.MaxValue with null
var reportlist = reports.OrderBy(n => n.Date = n.Date == null ? n.Date = DateTime.MaxValue : n.Date).Select(n=>n = new Report() {Date= n.Date == DateTime.MaxValue ? n.Date = null : n.Date, Id=n.Id }).ToList();
foreach (var report in reportlist)
{
Console.WriteLine("ID = " + report.Id + " " + "Date = " + report.Date);
}

Related

Convert BSON Document string property to Datetime object

I stored data on Mongo db as below document
public class BookingDocument{
public string Id {get;set;}
public List<ActivityDocument> Activities {get;set;}
public string Status {get;set;}
}
public class ActivityDocument {
public string DateFrom {get;set;}
public string Status {get;set;}
}
I have to filter BookingList Collection with the requested date pass from user
public async Task<List<BookingDocument>> ActivityBookingList(string start,string end)
{
DateTime startDate;
DateTime endDate;
startDate = DateTime.ParseExact(start + " " + "00:00:00", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
endDate = DateTime.ParseExact(end + " " + "00:00:00", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
**solution 1**
var filter = new BsonDocument("$expr", new BsonDocument(
"$and", new BsonArray{
new BsonDocument("$gte",new BsonArray{
new BsonDocument("$dateFromString","$Activities.DateFrom"), startDate.ToString("yyyy-MM-dd")
}),
new BsonDocument("$lte",new BsonArray{
new BsonDocument("$dateFromString","$Activities.DateFrom"), endDate.ToString("yyyy-MM-dd")
})
}
));
totalCount = await BookingCollection
.Find(Builders<BookingDocument>.Filter.And(filter))
.CountDocumentsAsync();
}
returns
$dateFromString only supports an object as an argument, found: string
error
I tried below options as well
Solution 2
var filter = new BsonDocument("$expr", new BsonDocument(
"$and", new BsonArray{
new BsonDocument("$gte",new BsonArray{
new BsonDocument("$toDate","$Activities.DateFrom"),startDate
}),
new BsonDocument("$lte",new BsonArray{
new BsonDocument("$toDate","$Activities.DateFrom"),endDate
})
}
));
totalCount = await BookingCollection
.Find(Builders<BookingDocument>.Filter.And(filter))
.CountDocumentsAsync();
}
return
Unsupported conversion from array to date in $convert with no onError
value
error
but below is return the output but it only checks first element in the activity list
var filter = new BsonDocument("$expr", new BsonDocument(
"$and", new BsonArray{
new BsonDocument("$gte",new BsonArray{
new BsonDocument("$dateFromString",new BsonDocument("dateString", new BsonDocument("$arrayElemAt", new BsonArray { "$Activities.DateFrom", 0 }))),startDate
}),
new BsonDocument("$lte",new BsonArray{
new BsonDocument("$dateFromString",new BsonDocument("dateString", new BsonDocument("$arrayElemAt", new BsonArray { "$Activities.DateFrom", 0 }))),endDate
})
}
));
totalCount = await BookingCollection
.Find(Builders<BookingDocument>.Filter.And(filter))
.CountDocumentsAsync();
please help to sort out this issue

LINQ to get unique id that has list of items

I am trying to generate a list result through linq.
I would like to have a result as a list with unique folder id with 0th item as folder_name, 1st Item as a list with one or more projects having fields project_id,name and description.
I have written following query:
Folders is basically model with format as folderid, name, List projects where Project Model has project_id, name and description
from the following records:
Models
public class FolderModel
{
public int folder_id { get; set; }
public string folder_name { get; set; }
public List<ProjectModel> projects{ get; set; }
}
public class ProjectModel
{
public int project_id { get; set; }
public string project_name { get; set; }
public string project_description { get; set; }
}
public class ResultModel
{
public List<FolderModel> folders { get; set; }
}
Result Data
List<FolderModel, List<ProjectModel>> result = new List<FolderModel, List<ProjectModel>>();
List<ProjectModel> projectList1 = new List<>();
ProjectModel projectModel1 = new ProjectModel();
projectModel1.project_name = "F1P1";
projectModel1.project_description = "F1P1";
projectList1.add(projectModel1);
List<ProjectModel> projectList2 = new List<>();
ProjectModel projectModel21 = new ProjectModel();
projectModel21.project_name = "F2P1";
projectModel21.project_description = "F2P1";
projectList2.add(projectModel21);
ProjectModel projectModel22 = new ProjectModel();
projectModel22.project_name = "F2P2";
projectModel22.project_description = "F2P2";
projectList2.add(projectModel22);
List<ProjectModel> projectList3 = new List<>();
ProjectModel projectModel3 = new ProjectModel();
projectModel3.project_name = "F3P1";
projectModel3.project_description = "F1P3";
projectList3.add(projectModel3);
ResultModel resultModel = new resultModel();
resultModel.(new FolderModel { folder_id: 1,folder-name: "F1" }, projectList1);
FolderModel folderModel1 = new FolderModel();
folderModel1.folder_id = 1
folderModel1.folder_name = "F1"
folderModel1.projects = projectList1
FolderModel folderModel2 = new FolderModel();
folderModel2.folder_id = 2
folderModel2.folder_name = "F2"
folderModel2.projects = projectList2
FolderModel folderModel3 = new FolderModel();
folderModel3.folder_id = 3
folderModel3.folder_name = "F3"
folderModel3.projects = projectList3
ResultModel resultModel = new ResultModel();
List<FolderModel> folderList = new List<>();
folderList.add(folderModel1);
folderList.add(folderModel2);
folderList.add(folderModel3);
resultModel.folders = folderList
SQL Data
folder_id | folder_name | project_id | project_name | project_description
1 F1 11 F1P1 F1P1
2 F2 21 F2P1 F2P1
2 F2 22 F2P2 F2P2
3 F3 31 F3P1 F3P1
4 F4 41 F4P1 F4P1
5 F5 51 F5P1 F5P1
This is what I have tried
var result = resultModel.folders.GroupBy(x => new { x.folder_id }).ToList();
I am sure that after group by I have to select name but not sure how can I generate project into a list and add it to main folder id. Can someone please guide on this.
You can query like this:
var result =
resultModel
.folders
.GroupBy(x => new { x.folder_id })
.Select(s => new
{
folder_id = s.Key,
folder_name = s.First().folder_name
})
.ToList();
It seems to me that you're looking for this:
var folders = new []
{
new { folder_id = 1, folder_name = "F1", project_id = 11, project_name = "F1P1", project_description = "F1P1" },
new { folder_id = 2, folder_name = "F2", project_id = 21, project_name = "F2P1", project_description = "F2P1" },
new { folder_id = 2, folder_name = "F2", project_id = 22, project_name = "F2P2", project_description = "F2P2" },
new { folder_id = 3, folder_name = "F3", project_id = 31, project_name = "F3P1", project_description = "F3P1" },
new { folder_id = 4, folder_name = "F4", project_id = 41, project_name = "F4P1", project_description = "F4P1" },
new { folder_id = 5, folder_name = "F5", project_id = 51, project_name = "F5P1", project_description = "F5P1" },
};
List<FolderModel> result =
folders
.GroupBy(
x => new { x.folder_id, x.folder_name },
x => new { x.project_id, x.project_name, x.project_description })
.Select(x => new FolderModel()
{
folder_id = x.Key.folder_id,
folder_name = x.Key.folder_name,
projects = x.Select(y => new ProjectModel()
{
project_id = y.project_id,
project_name = y.project_name,
project_description = y.project_description,
}).ToList(),
})
.ToList();

How to update AmountDue value by InvoiceId in XERO API using C#

I am getting the list of Invoice details by Invoice Id.
Now i want to update AmountDue by respective Invoice Id.
i tried by below code:
ByInvoiceId.AmountDue = Convert.ToDecimal(100.00);
public_app_api.Invoices.Update(ByInvoiceId);
but..Error as
"A validation exception occurred"
What's the reason behind and How to solve this?
There are a number of ways to change the amount due on an invoice, however changing the value of the property directly is not one of them.
The amount due on an invoice is driven by the totals of the line items on the invoice minus the total of payments and allocated credit. One way to change the amount due is to change the values of your line items or add/remove some line items. You won't be able to change the invoice if it has been paid/partially paid.
Another way you could change the amount due on an invoice is to add a payment against the invoice or allocate credit from a credit note, prepayment, or overpayment to the invoice
In addition to MJMortimer's answer.
You can't change the line amounts on an AUTHORISED invoice via the c# API. You have to VOID the invoice and create a new one. You can however update DRAFT and SUBMITTED ones by updating the line items.
EDIT: Here is some code to help you. This is create invoice code, but amending one is essentially the same.
public XeroTransferResult CreateInvoices(IEnumerable<InvoiceModel> invoices, string user, string status)
{
_user = XeroApiHelper.User(user);
var invoicestatus = InvoiceStatus.Draft;
if (status == "SUBMITTED")
{
invoicestatus = InvoiceStatus.Submitted;
}
else if (status == "AUTHORISED")
{
invoicestatus = InvoiceStatus.Authorised;
}
var api = XeroApiHelper.CoreApi();
var xinvs = new List<Invoice>();
foreach (var inv in invoices)
{
var items = new List<LineItem>();
foreach (var line in inv.Lines)
{
decimal discount = 0;
if (line.PriceBeforeDiscount != line.Price)
{
discount = (decimal)(1 - line.Price / line.PriceBeforeDiscount) * 100;
}
items.Add(new LineItem
{
AccountCode = line.AccountCode,
Description = line.PublicationName != "N/A" ? line.PublicationName + " - " + line.Description : line.Description,
TaxAmount = (decimal)line.TaxAmount,
Quantity = 1,
UnitAmount = (decimal)line.PriceBeforeDiscount,
DiscountRate = discount,
TaxType = line.XeroCode,
ItemCode = line.ItemCode
});
}
var person = inv.Company.People.FirstOrDefault(p => p.IsAccountContact);
if (person == null)
{
person = inv.Company.People.FirstOrDefault(p => p.IsPrimaryContact);
}
var ninv = new Invoice
{
Number = inv.ClientInvoiceId,
Type = InvoiceType.AccountsReceivable,
Status = invoicestatus,
Reference = inv.Reference,
Contact = new Contact
{
Name = inv.Company.OrganisationName,
//ContactNumber = "MM" + inv.Company.CompanyId.ToString(),
FirstName = person.FirstName,
LastName = person.LastName,
EmailAddress = person.Email,
Phones = new List<Phone>()
{
new Phone {PhoneNumber = person.Telephone, PhoneType = PhoneType.Default},
new Phone {PhoneNumber = person.Mobile, PhoneType = PhoneType.Mobile}
},
Addresses = new List<Address>
{ new Address
{
//AttentionTo = inv.Company.People.FirstOrDefault(p => p.IsAccountContact) == null
//? inv.Company.People.FirstOrDefault(p=> p.IsPrimaryContact).FullName
//: inv.Company.People.FirstOrDefault(p => p.IsAccountContact).FullName,
//AddressLine1 = inv.Company.OrganisationName,
AddressLine1 = inv.Company.Address.Address1,
AddressLine2 = inv.Company.Address.Address2 ?? "",
AddressLine3 = inv.Company.Address.Address3 ?? "",
Region = inv.Company.Address.CountyState,
City = inv.Company.Address.TownCity,
PostalCode = inv.Company.Address.PostCode,
}
}
},
AmountDue = (decimal)inv.TotalAmount,
Date = inv.InvoiceDate,
DueDate = inv.DueDate,
LineItems = items,
LineAmountTypes = LineAmountType.Exclusive
};
if (SessionContext.TransferContactDetailsToXero == false)
{
ninv.Contact = new Contact
{
Id = inv.Company.XeroId ?? Guid.Empty,
Name = inv.Company.OrganisationName
};
}
xinvs.Add(ninv);
}
var success = true;
var xinvresult = new List<Invoice>();
try
{
api.SummarizeErrors(false);
xinvresult = api.Invoices.Create(xinvs).ToList();
}
catch (ValidationException ex)
{
// Something's gone wrong
}
foreach (var inv in xinvresult)
{
var mminvoice = invoices.FirstOrDefault(i => i.ClientInvoiceId == inv.Number);
if (inv.Errors != null && inv.Errors.Count > 0)
{
success = false;
if (mminvoice != null)
{
var errors = new List<XeroError>();
foreach (var err in inv.Errors)
{
errors.Add(new XeroError { ErrorDescription = err.Message });
}
mminvoice.XeroErrors = errors;
}
}
else
{
mminvoice.XeroTransferDate = DateTime.Now;
mminvoice.XeroId = inv.Id;
mminvoice.XeroErrors = new List<XeroError>();
}
}
return new XeroTransferResult
{
Invoices = invoices,
Success = success
};
}

Display column name from column data in Entity Framework

I have a data with following structure. I am using Entity Framework.
Id fileName date status
---------------------------------------------
1 file1 12-05-2016 11:30 fail
2 file1 12-05-2016 11:35 success
3 file2 13-05-2016 12:01 success
4 file2 13-05-2016 12.02 fail
5 file1 13-05-2016 success
6 file3 13-05-2016 fail
I want result like this
fileName 12-05-2016 13-05-2016
------------------------------------------
file1 success sucess
file2 fail
file3 fail
Criteria - Search the data between two dates and all dates file status should be displayed in above way. For the same day same file's two entries exist, then latest status will be displayed.
I am using code first approach to get data.
this is my code at repo
IQueryable<FileData> filedata=this.context.FileData;
I created a pivot table based on Svek code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
FileStatus filestatus = new FileStatus();
filestatus.Load();
DataTable pivot = filestatus.PivotTable();
}
}
public class FileStatus
{
public static List<FileStatus> filedata = new List<FileStatus>();
public int? Id { get; set; }
public string filename { get; set; }
public DateTime date { get; set; }
public string status { get; set; }
public void Load()
{
filedata = new List<FileStatus>()
{
new FileStatus(){ Id = 1, filename = "file1", date = new DateTime(2016,05,12,11,30,00), status = "fail"},
new FileStatus(){ Id = 2, filename = "file1", date = new DateTime(2016,05,12,11,35,00), status = "success"},
new FileStatus(){ Id = 3, filename = "file2", date = new DateTime(2016,05,13,12,01,00), status = "success"},
new FileStatus(){ Id = 4, filename = "file2", date = new DateTime(2016,05,13,12,02,00), status = "fail"},
new FileStatus(){ Id = 5, filename = "file1", date = new DateTime(2016,05,13,12,30,00), status = "success"},
new FileStatus(){ Id = 6, filename = "file3", date = new DateTime(2016,05,13,12,31,00), status = "fail"}
};
}
public DataTable PivotTable()
{
DataTable pivot = new DataTable();
DateTime[] uniqueDates = filedata.Select(x => x.date.Date).Distinct().OrderBy(x => x).ToArray();
pivot.Columns.Add("filename", typeof(string));
foreach (DateTime date in uniqueDates)
{
pivot.Columns.Add(date.ToString("MM-dd-yyyy"), typeof(string));
}
var groups = filedata.GroupBy(x => x.filename).ToList();
foreach (var group in groups)
{
DataRow newRow = pivot.Rows.Add();
newRow["filename"] = group.Key;
foreach (FileStatus filestatus in group)
{
newRow[filestatus.date.ToString("MM-dd-yyyy")] = filestatus.status;
}
}
return pivot;
}
}
}
First of all, you have to pay me for that, hahaha, all the example is wrong (repeats, year 1016¿?, hour with . instead of :, and without hour), I check you has written quickly...so:
declare #cols nvarchar(max)
declare #query nvarchar(max)
CREATE TABLE [dbo].[Table_1](
[id] [int] NULL,
[filename] [nvarchar](50) NULL,
[date] [datetime] NULL,
[status] [nvarchar](50) NULL
) ON [PRIMARY]
insert into table_1
values
(1 ,'file1' ,'12-05-2016 11:30:00.000' ,'fail'),
(2 ,'file1' ,'12-05-2016 11:35:00.000' ,'success'),
(3 ,'file2' ,'13-05-2016 12:01:00.000' ,'success'),
(3 ,'file2' ,'13-05-2016 12:02:00.000' ,'fail'),
(4 ,'file1' ,'13-05-2016 12:03:00.000' ,'success'),
(5 ,'file3' ,'13-05-2016 12:04:00.000' ,'fail')
select t2.filename,dat, status
into #temp1
FROM
(select filename, cast([date] as date) as dat, max([date]) as maxdat
from table_1
group by filename, cast([date] as date)
) t1
INNER JOIN
table_1 t2
on t1.filename = t2.filename
and t2.[date] = t1.maxdat
and cast(t2.date as date) = t1.dat
--select * from #temp1
--after that you want pivot by date and max status for example¿?
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(convert(CHAR(10), datelist, 120))
from
(
select distinct cast(dat as date) as datelist from #temp1
)t1
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
--select #cols
set #query =
('select filename, ' + #cols + '
from #temp1
pivot (
max(status)
for dat in (' + #cols + ')
)p
')
print #query
exec(#query)
Hope this help you! $$
Based on your question, here is an example class that would work
public class FileStatus
{
public int? Id { get; set; }
public string Filename { get; set; }
public DateTime Date { get; set; }
public string Status { get; set; }
}
Here is a working sample that would get you the result you want, so that you can pass it onto your report template:
var filedata= new List<FileStatus>()
{
new FileStatus(){ Id = 1, Filename = "file1", Date = new DateTime(2016,05,12,11,30,00), Status = "fail"},
new FileStatus(){ Id = 2, Filename = "file1", Date = new DateTime(2016,05,12,11,35,00), Status = "success"},
new FileStatus(){ Id = 3, Filename = "file2", Date = new DateTime(2016,05,13,12,01,00), Status = "success"},
new FileStatus(){ Id = 4, Filename = "file2", Date = new DateTime(2016,05,13,12,02,00), Status = "fail"},
new FileStatus(){ Id = 5, Filename = "file1", Date = new DateTime(2016,05,13,12,30,00), Status = "success"},
new FileStatus(){ Id = 6, Filename = "file3", Date = new DateTime(2016,05,13,12,31,00), Status = "fail"}
};
//remove the above and replace it with your own:
//IQueryable<FileData> filedata = this.context.FileData;
var result = filedata.GroupBy(c => new { c.Filename, c.Date.Date }).Select(c => new
{
Row = c.Key.Filename,
Column = c.Key.Date,
Value = filedata.FirstOrDefault(co => co.Id == c.Max(max => max.Id)).Status
}).OrderBy(c => c.Row).OrderBy(c => c.Column);

How to convert table format to string programmatically

Good day all,
would like request to how to convert table format to string
eg:
Material Control August
Development September
Planning August
HR September
to
September: Development, HR
August : Material Control, Planning
List<String> returnvalueStringMonth = new List<String>();
List<String> returnvalueStringDept = new List<String>();
foreach (DataRow dr in dsSeries.Tables[0].Rows)
{
string newmanout = dr["MonthNames"].ToString();
returnvalueStringMonth.Add(newmanout);
string Departs = dr["Depart"].ToString();
returnvalueStringMonth.Add(Departs);
//var DDLName = dr["Depart"];
//Label dynamicLabel = new Label();
//dynamicLabel.Text = DDLName.ToString() + ",";
//div1.Controls.Add(dynamicLabel);
//var sumPlus = Convert.ToDouble(newmanout) +",";
}
List<string> b = new List<string>();
b.AddRange(returnvalueStringMonth.Distinct());
for (int cs = 0; cs < b.Count; cs++)
{
//Panel aspPanel = new Panel();
Label dynamicLabel = new Label();
dynamicLabel.Text = b[cs].ToString()+":" + "<br/>";
div1.Controls.Add(dynamicLabel);
}
I able achive until month only, then i realize made mistake.
So, please advise how to achive this.
The code below will fill a list of strings with your desired output. You can change the second loop to do what you want.
var monthList = new Dictionary<String, List<String>>();
foreach (DataRow dr in dsSeries.Tables[0].Rows)
{
var key = dr["MonthName"].ToString();
var value = dr["Department"].ToString();
if (!monthList.ContainsKey(key))
{
monthList.Add(key, new List<string>());
}
monthList[key].Add(value);
}
List<string> b = new List<String>();
foreach (var month in monthList.Keys)
{
b.Add(month + ": " + String.Join(", ", monthList[month])");
}
If you would rather use LINQ, you can do this instead:
var q = from row in dsSeries.Tables[0].AsEnumerable()
group row by row["Month"] into qGrouped
orderby qGrouped.Key
select String.Format("{0}: {1}", qGrouped.Key,
String.Join(", ", Array.ConvertAll(qGrouped.ToArray(), r => r["Department"])));
var b = q.ToList();
public class TestClass
{
public string S1 { get; set; }
public string S2 { get; set; }
}
[TestMethod]
public void MyTest()
{
// Material Control August
//Development September
//Planning August
//HR September
var list = new List<TestClass>
{
new TestClass {S1 = "Material Control", S2 = "August"},
new TestClass {S1 = "Development", S2 = "September"},
new TestClass {S1 = "Planning", S2 = "August"},
new TestClass {S1 = "HR", S2 = "September"}
};
var listGroupByMonth = list.GroupBy(l => l.S2);
foreach (var lstByMonth in listGroupByMonth)
{
var key = lstByMonth.Key;
var finalValue = string.Join(", ", lstByMonth.ToList().Select(lbm => lbm.S1));
}
}

Categories