Adding index field to LINQ List <T> results using C# - c#

I'm using a generic list. For example (with some properties):
public class randomList
{
public string propertyA { get; set; }
public string propertyB { get; set; }
public string propertyC { get; set; }
}
So on my retrieving query I used to write the following:
_grouppedResto.Select((value, index) => new { index = index, value = value });
dgvHeader.DataSource = _grouppedResto;
But now it shows blank on index column. I will like to get something like this :
this is all about the datagrid :
this.dgvHeader.AllowUserToAddRows = false;
this.dgvHeader.AllowUserToDeleteRows = false;
this.dgvHeader.AllowUserToResizeRows = false;
this.dgvHeader.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvHeader.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.FECRGV,
this.TDORGV,
this.NDORGV,
this.RUCCLI,
this.RAZCLI,
this.VVTRGVS,
this.IGVRGVS,
this.TOTRGVS,
this.TCARGV,
this.VVTRGVD,
this.IGVRGVD,
this.TOTRGVD});
this.dgvHeader.Location = new System.Drawing.Point(12, 128);
this.dgvHeader.Name = "dgvCACD";
this.dgvHeader.Size = new System.Drawing.Size(1265, 611);
this.dgvHeader.TabIndex = 13;
**dgvHeader.AutoGenerateColumns = false;**
How can I resolve this?

It looks like you need to assign _grouppedResto to an anonymous type as in:
var yourSequence = _groupedResto.Select((value, index) => new { index = index, value = value });
dgvHeader.DataSource = yourSequence;
I'd be happy to help with any particulars you care to provide.
Good luck, hope this helped :)

To combine the index with the properties of your list element you need to change your select statement into something like this:
_grouppedResto.Select(
(value, index) => new {
index = index, propertyA = value.propertyA, propertyB = value.propertyB
}
);

Well, I use this way to solve this... (I think is the worst way, cause you have to modified the domain class)
public class RGVCAFAC
{
public int index { get; set; }
public string CODEAUX { get; set; }
public string FECRGV { get; set; }
public string TDORGV { get; set; }
public string MONRGV { get; set; }
public string NDORGV { get; set; }
public string RUCCLI { get; set; }
public string RAZCLI { get; set; }
public string CDCRGV { get; set; }
public string TERRGV { get; set; }
public string PDSRGV { get; set; }
public double VVTRGVS { get; set; }
public double IGVRGVS { get; set; }
public double TOTRGVS { get; set; }
public string TCARGV { get; set; }
public double VVTRGVD { get; set; }
public double IGVRGVD { get; set; }
public double TOTRGVD { get; set; }
public string PACEST { get; set; }
public string CODUNI { get; set; }
public string DIRCLI { get; set; }
public string TELCLI { get; set; }
public int PFLAG { get; set; }
//I have to add the following, so generators are useless :(
public RGVCAFAC()
{
}
public RGVCAFAC(RGVCAFAC x)
{
this.CODEAUX = x.CODEAUX;
this.FECRGV = x.FECRGV;
this.TDORGV = x.TDORGV;
this.MONRGV = x.MONRGV;
this.RUCCLI = x.RUCCLI;
this.RAZCLI = x.RAZCLI;
this.CDCRGV = x.CDCRGV;
this.TERRGV = x.TERRGV;
this.PDSRGV = x.PDSRGV;
this.VVTRGVS = x.VVTRGVS;
this.IGVRGVS = x.IGVRGVS;
this.TOTRGVS = x.TOTRGVS;
this.TCARGV = x.TCARGV;
this.VVTRGVD = x.VVTRGVD;
this.IGVRGVD = x.IGVRGVD;
this.TOTRGVD = x.TOTRGVD;
this.PACEST = x.PACEST;
this.CODUNI = x.CODUNI;
this.DIRCLI = x.DIRCLI;
this.TELCLI = x.TELCLI;
this.PFLAG = x.PFLAG;
}
}
and finally :
var yourSequence = _grouppedResto.
Select((value, index) => new RGVCAFAC(value) { index = index+1, rgvcafac = value }).ToList(); //need to begin on 1 not on 0
dgvCabecera.DataSource = yourSequence;

int theIndex = 1;
foreach(var x in _grouppedResto)
{
x.index = theIndex;
theIndex += 1;
}

Related

System.InvalidCastException: 'Object cannot be cast from DBNull to other types.' in Conversion from Database to Object

I have a problem when i try to set a DateTime from my datebase. i am having a DBnull tjek. and i have made my Datetime nullabel. cant figurer out why.
public static List<ExportElements> GetExportElementsForCase(int caseNumber)
{
using (var dataAccess = new DbConnection<SqlConnection>())
{
DataTable dbExportElements = new DataTable();
dataAccess.ExecuteCommand<DataTable>(command =>
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "GetElementsForEksport";
var caseNr = command.CreateParameter();
caseNr.ParameterName = "#caseNumberTolookUp";
caseNr.Value = caseNumber;
command.Parameters.Add(caseNr);
var reader = command.ExecuteReader();
//Create a new DataTable.
DataTable resultToReturn = new DataTable("exportElements");
//Load DataReader into the DataTable.
resultToReturn.Load(reader);
dbExportElements = resultToReturn;
return resultToReturn;
});
List<ExportElements> exportMarterials = new List<ExportElements>();
exportMarterials = (from DataRow dr in dbExportElements.Rows
select new ExportElements()
{
CaseNumber = Convert.ToInt32(dr["CaseNumber"]),
SubCaseNumber = Convert.ToInt32(dr["SubCaseNumber"]),
ElementNumber = dr["ElementNumber"].ToString(),
Side3To4 = Convert.ToDouble(dr["Side3To4"]),
Side2To5 = Convert.ToDouble(dr["Side2To5"]),
Side1To6 = Convert.ToDouble(dr["Side1To6"]),
Weight = Convert.ToDouble(dr["Weight"]),
Volume = Convert.ToDouble(dr["Volume"]),
ProductNumber = Convert.ToInt32(dr["ProductNumber"]),
DepartmentNumber = Convert.ToInt32(dr["DepartmentNumber"]),
TurnElement = Convert.ToBoolean(dr["TurnElement"]),
ErektionSeqence = Convert.ToInt32(dr["ErektionSeqence"]),
ID = Convert.ToInt32(dr["ID"]),
ReleasedDate = dr["ReleasedDate"] == DBNull.Value ? (DateTime?)null : Convert.ToDateTime(dr["ReleasedDate"]),
ElementBasicPart = dr["ElementBasicPart"].ToString(),
RevisionsLetter = dr["RevisionsLetter"].ToString(),
ElementStatus = Convert.ToInt32(dr["ElementStatus"]),
RevisionsText = dr["RevisionsText"].ToString(),
EnvironmentalClass = Convert.ToInt32(dr["EnvironmentalClass"]),
LedgeHeight1 = Convert.ToDouble(dr["LedgeHeight1"]),
LedgeHeight2 = Convert.ToDouble(dr["LedgeHeight2"]),
IsClosed = Convert.ToBoolean(dr["IsClosed"]),
RevitTemplate = dr["revitTemplate"].ToString(),
}).ToList();
return exportMarterials;
}
}
It is the releaseDate that fails.
The Model i am converting to from the DataRow.
public class ExportElements
{
public int CaseNumber { get; set; }
public int SubCaseNumber { get; set; }
public string ElementNumber { get; set; }
public double Side3To4 { get; set; }
public double Side2To5 { get; set; }
public double Side1To6 { get; set; }
public double Weight { get; set; }
public double Volume { get; set; }
public int ProductNumber { get; set; }
public int DepartmentNumber { get; set; }
public bool TurnElement { get; set; }
public int ErektionSeqence { get; set; }
public int ID { get; set; }
public DateTime? ReleasedDate { get; set; }
public string ElementBasicPart { get; set; }
public string RevisionsLetter { get; set; }
public int ElementStatus { get; set; }
public string RevisionsText { get; set; }
public int EnvironmentalClass { get; set; }
public double LedgeHeight1 { get; set; }
public double LedgeHeight2 { get; set; }
public bool IsClosed { get; set; }
public string RevitTemplate { get; set; }
}
It works in other conversion with the same Datarow to DateTime conversion
I found the problem. it was not the DateTime? but the "ErektionSeqence" that was also DBNull witch i forgot to make a check for.
Instead of using all those Convert calls when you're not actually converting anything, I suggest that you use the Field method from LINQ to DataSet. It can handle nulls. E.g.
NonNullableReferenceTypeProperty = row.Field<string>("Column1"),
NullableReferenceTypeProperty = row.Field<string>("Column2"),
NonNullableValueTypeProperty = row.Field<DateTime>("Column3"),
NullableValueTypeProperty = row.Field<DateTime?>("Column4"),

Large object on ViewState

I am storing object of a class on a ViewState. It has 3 string variables. But when ever one string gets larger (more than 400 chars) Pagination stops working.
I have tried so many things but no luck.
So I need to think of another Session Management method?
public class Productx
{
public bool check { get; set; } // ForMultiProduct Page - Selected or not
public string imagePathSmall { get; set; }
public string imagePathLarge { get; set; }
public int Id { get; set; }
public int RatingCount { get; set; }
public string SetName { get; set; }
public string Description { get; set; }
public string KeyWords { get; set; }
public int FavourCount { get; set; }
}
public List<Productx> ArticleList
{
get
{
if (this.ViewState["ArticleList"] != null)
{
return (List<Productx>)(this.ViewState["ArticleList"]);
}
return new List<Productx>();
}
set { this.ViewState["ArticleList"] = value; }
}
List<Productx> al = new List<Productx>();
foreach (DataRow dr in tblProducts.Rows)
{
Productx a = new Productx();
a.check = false;
a.Id = Convert.ToInt32(dr["ID"].ToString());
a.RatingCount = Convert.ToInt32(dr["RATING_COUNT_BY_CAT"].ToString());
string s = dr["KEY_WORDS"].ToString();
a.KeyWords = s;
a.FavourCount = Convert.ToInt32(dr["FAVORITE_COUNT"].ToString());
al.Add(a);
}
if (al.Count > 0) ArticleList = al;

Executing Actions within Actions for collection without creating new collection

I have collection of objects where each object contains other collections of objects. All I want to modify my original collection of objects in a way, that no extra memory should be allocated. Everything should happen in memory.
I am looking for some templatized Action or Func so that with the mixture of declarative and functional approach, no new collection is formed and in memory my original collection is also modified.
Following is the hierarchy of collection
public class ConsignmentAddress
{
public int ConsignmentAddressId { get; set; }
public int AddressTypeId { get; set; }
public string Street { get; set; }
public string Town { get; set; }
public string ZipCode { get; set; }
public int ConsignmentId { get; set; }
}
public class ConsignmentLine
{
public int ConsignmentLineId { get; set; }
public int PackagingId { get; set; }
public double Amount { get; set; }
public double Weight { get; set; }
public int ConsignmentId { get; set; }
public int? PackagingAidId { get; set; }
}
public class PackagingAid
{
public int PackagingAidId { get; set; }
public int ConsignmentId { get; set; }
public int PackagingId { get; set; }
public double Quantity { get; set; }
}
public class Consignment
{
public int ConsignmentId { get; set; }
public int ClientSubsidiaryId { get; set; }
public int ForwarderId { get; set; }
public int Sourcepaty { get; set; }
public int ParentId { get; set; }
public int ProductId { get; set; }
public ICollection<PackagingAid> PackagingAids { get; set; }
public ICollection<ConsignmentLine> ConsignmentLines { get; set; }
public ICollection<ConsignmentAddress> ConsignmentAddresses { get; set; }
public Consignment()
{
PackagingAids = new List<PackagingAid>();
ConsignmentLines = new List<ConsignmentLine>();
ConsignmentAddresses = new List<ConsignmentAddress>();
}
}
My intention is to write generic extension method which should operate on all kind of objects in the hierarchy I mentioned above.
public static class ConsignmentExtension
{
public static T Set<T>(this T input, Action<T> updater)
{
updater(input);
return input;
}
}
Where as my client code is which is first getting list of 10000 of objects in list and just resetting few properties of ( consignment, consignmentaddresses for corresponding consignment, consignmentlines of corresponding consignment and packagingaid of corresponding consignment)
My written Foreach approach worked fine but i want templatized and efficient approach for the same collection.
consignments.ForEach(cons =>
{
cons.ConsignmentId = -1;
cons.ConsignmentAddresses.ToList().ForEach(address =>
{
address.ConsignmentId = -1;
address.ConsignmentAddressId = -1;
});
cons.ConsignmentLines.ToList().ForEach(line =>
{
line.ConsignmentId = -1;
line.ConsignmentLineId = -1;
line.PackagingAidId = -1;
});
cons.PackagingAids.ToList().ForEach(aid =>
{
aid.ConsignmentId = -1;
aid.PackagingAidId = -1;
});
});
But I am looking for something like declarative style.
var updatedConsignments = from consignment in consignments
select consignment.Set<Consignment>(con =>
{
con.ConsignmentId = -1;
con.ConsignmentAddresses.Set<dynamic>(address => { address.ConsignmentId = -1; address.ConsignmentAddressId = -1; });
con.ConsignmentLines.Set<dynamic>(line => { line.PackagingAidId = -1; line.ConsignmentId = -1;line.ConsignmentLineId = -1; });
con.PackagingAids.Set<dynamic>(aid => { aid.ConsignmentId = -1; aid.PackagingAidId = -1; });
});
Is that possible somehow?
Thanks in advance.
This could be written as
public static class ConsignmentExtension
{
public static IEnumerable<dynamic> SetEach(this IEnumerable<dynamic> input, Action<dynamic> updater)
{
foreach (var item in input)
{
updater(item);
}
return input;
}
}
Usage:
var addresses = new []
{
new ConsignmentAddress()
};
addresses.SetEach(a => a.ConsignmentId = -1);
var packages = new []
{
new PackagingAid()
};
packages.SetEach(p => p.PackagingAidId = -1);

C# sort datagridview on column header click

:)
I have a datagridview and I fill it by List (I get data from 2 text files), but when I tried to click on a column header (I tried with all columns headers), I can't sort my datagridview data. This is my code:
public class Data1
{
public string Campionato { get; set; }
public string Data { get; set; }
public string Home { get; set; }
public string Away { get; set; }
public int HSFT { get; set; }
public int ASFT { get; set; }
public int HSHT { get; set; }
public int ASHT { get; set; }
public int HSSH { get; set; }
public int ASSH { get; set; }
}
public class Data2
{
public string Home { get; set; }
public string Away { get; set; }
public int HSFT { get; set; }
public int ASFT { get; set; }
public string HODD { get; set; }
public string XODD { get; set; }
public string AODD { get; set; } //no name in sample
public string Data { get; set; }
public string RisFin { get; set; } //no name in sample
public string Over05SH { get; set; }
public string Over05HT { get; set; }
public string Over15HT { get; set; }
public string Over05FT { get; set; }
public string Over15FT { get; set; }
public string Over25FT { get; set; }
public string Over35FT { get; set; }
public string Over45FT { get; set; }
}
public class CombinedData
{
public string Campionato { get; set; }
public string Data { get; set; }
public string Home { get; set; }
public string Away { get; set; }
public int HSFT { get; set; }
public int ASFT { get; set; }
public int HSHT { get; set; }
public int ASHT { get; set; }
public int HSSH { get; set; }
public int ASSH { get; set; }
public string HODD { get; set; }
public string XODD { get; set; }
public string AODD { get; set; } //some name
public string RisFin { get; set; } //no name in sample
public string Over05SH { get; set; }
public string Over05HT { get; set; }
public string Over15HT { get; set; }
public string Over05FT { get; set; }
public string Over15FT { get; set; }
public string Over25FT { get; set; }
public string Over35FT { get; set; }
public string Over45FT { get; set; }
}
var data1 = File.ReadAllLines("read" + campionatoselezTxt.Text + "stats.txt").ToList();
var data2 = File.ReadAllLines("read" + campionatoselezTxt.Text + "bex.txt").ToList();
var dataList1 = new List<Data1>();
foreach (var data in data1)
{
var columns = data.Split(';');
dataList1.Add(new Data1
{
Campionato = columns[0],
Data = columns[1],
Home = columns[2],
Away = columns[3],
HSFT = int.Parse(columns[4]),
ASFT = int.Parse(columns[5]),
HSHT = int.Parse(columns[6]),
ASHT = int.Parse(columns[7]),
HSSH = int.Parse(columns[8]),
ASSH = int.Parse(columns[9])
//other int properties
});
}
var dataList2 = new List<Data2>();
foreach (var data in data2)
{
var columns = data.Split(';');
dataList2.Add(new Data2
{
Home = columns[0],
Away = columns[1],
HODD = columns[4],
XODD = columns[5],
AODD = columns[6],
});
}
var combinedDataList = from d1 in dataList1
//join d2 in dataList2 on d1.Home equals d2.Home
join d2 in dataList2 on new { d1.Home, d1.Away } equals new { d2.Home, d2.Away }
select new CombinedData
{
Campionato = d1.Campionato,
Data = d1.Data,
Home = d2.Home,
Away = d2.Away,
HSFT = d1.HSFT,
ASFT = d1.ASFT,
HSHT = d1.HSHT,
ASHT = d1.ASHT,
HSSH = d1.HSSH,
ASSH = d1.ASSH,
HODD = d2.HODD,
XODD = d2.XODD,
AODD = d2.AODD,
RisFin = d2.RisFin,
Over05SH = d2.Over05SH
}; //map all properties
finabexDgv.DataSource = combinedDataList.ToList();
finabexDgv.AllowUserToOrderColumns = true;
I'd like to have a possibility to sort by clicking columns headers.
I need your advices, please :)
Happy Sunday!
On your desing view, search the "ColumnHeaderMouseClick" and double click on the empty field.
on the new function, apply some code like this:
dgv_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (dgv.Columns[e.ColumnIndex].SortMode != DataGridViewColumnSortMode.NotSortable)
{
if (e.ColumnIndex == newSortColumn )
{
if (newColumnDirection == ListSortDirection.Ascending)
newColumnDirection = ListSortDirection.Descending;
else
newColumnDirection = ListSortDirection.Ascending;
}
newSortColumn = e.ColumnIndex;
switch (newColumnDirection)
{
case ListSortDirection.Ascending:
dgv.Sort(dgv.Columns[newSortColumn], ListSortDirection.Ascending);
break;
case ListSortDirection.Descending:
dgv.Sort(dgv.Columns[newSortColumn], ListSortDirection.Descending);
break;
}
}
}
and at the top of the class, add two private variables:
int newSortColumn;
ListSortDirection newColumnDirection = ListSortDirection.Ascending;
This will work if you don't have anything else rare at your source code.
Note: This code is not mine, i got it form here at stackoverflow

NullReferenceException attempting to access a list located in a class?

I am attempting to retrieve information using the Steam API. I created the classes offerStuff and itemsClass, offerStuff contains public List<itemsClass> items { get; set; }, however, whenever I attempt to access this list through os.items.Add(item), my program crashes with NullReferenceException. Is there some declaration I am missing? If so, how would I declare it so I can access it without the exception?
public static List<offerStuff> pollOffers()
{
using (dynamic tradeOffers = WebAPI.GetInterface("IEconService", config.API_Key))
{
List<offerStuff> OfferList = new List<offerStuff>();
offerStuff os = new offerStuff();
KeyValue kvOffers = tradeOffers.GetTradeOffers(get_received_offers: 1);//, active_only: 1
foreach (KeyValue kv in kvOffers["trade_offers_received"].Children)
{
os.tradeofferid = kv["tradeofferid"].AsInteger(); ;
os.accountid_other = Convert.ToUInt64(kv["accountid_other"].AsInteger());
os.message = kv["message"].AsString();
os.trade_offer_state = kv["trade_offer_state"].AsInteger();
foreach (KeyValue kv2 in kv["items_to_receive"].Children)
{
itemsClass item = new itemsClass();
item.appid = (kv2["appid"].AsInteger());
item.assetid = kv2["assetid"].AsInteger();
item.classid = kv2["classid"].AsInteger();
item.instanceid = kv2["instanceid"].AsInteger();
item.amount = kv2["amount"].AsInteger();
item.missing = kv2["missing"].AsInteger();
os.items.Add(item);
}
os.is_our_offer = kv["is_our_offer"].AsBoolean();
os.time_created = kv["time_created"].AsInteger();
os.time_updated = kv["time_updated"].AsInteger();
OfferList.Add(os);
}
return OfferList;
}
}
}
public class offerStuff
{
public int tradeofferid { get; set; }
public SteamID accountid_other { get; set; }
public string message { get; set; }
public int trade_offer_state { get; set; }
public List<itemsClass> items { get; set; }
public bool is_our_offer { get; set; }
public int time_created { get; set; }
public int time_updated { get; set; }
}
public class itemsClass
{
public int appid { get; set; }
public int assetid { get; set; }
public int classid { get; set; }
public int instanceid { get; set; }
public int amount { get; set; }
public int missing { get; set; }
}
The problem is probably that you're not initializing the collection items. You could do it on your contructor like this
public offerStuff()
{
items = new List<itemsClass>();
}

Categories