return multiple reader.cast<> - c#

All I want to do is return multiple reader.cast<> so that i can use 2 sqlcommands.
var first =reader.Cast<IDataRecord>().Select(x => new LocationInfo()
{
Names = x.GetString(0),
Values = Math.Round(x.GetDouble(1), 2).ToString("#,##0.00"),
ValuesDouble = x.GetDouble(1)
}).ToList();
reader.NextResult();
var second=reader.Cast<IDataRecord>().Select(x => new LocationInfo()
{
Names2 = x.GetString(0),
Values2 = Math.Round(x.GetDouble(1), 2).ToString("#,##0.00"),
ValuesDouble2 = x.GetDouble(1)
}).ToList();
All I want to do is return var first and var second. Please help :(
I'm using this Location.cs for parameters:
namespace MVCRealtime
{
public class LocationInfo
{
public string Names { get; set; }
public string Values { get; set; }
public double ValuesDouble { get; set; }
public string Names2 { get; set; }
public string Values2 { get; set; }
public double ValuesDouble2 { get; set; }
}
}

public static class ReaderHelper
{
public static IEnumerable<TElem> GetData<TElem>(this IDataReader reader, Func<IDataRecord, TElem> buildObjectDelegat)
{
while (reader.Read())
{
yield return buildObjectDelegat(reader);
}
}
}
// ...
var result = reader.GetData(x => new LocationInfo()
{
Names = x.GetString(0),
Values = Math.Round(x.GetDouble(1), 2).ToString("#,##0.00"),
ValuesDouble = x.GetDouble(1)
}).Take(2);
So you get 1st var in 1st element of the result and 2nd var in 2nd element.

Related

Map one class data to another class with iteration

I have a C# project and looking for simple solution for map one class object data to list of another class object.
This is my input class
public class RatesInput
{
public string Type1 { get; set; }
public string Break1 { get; set; }
public string Basic1 { get; set; }
public string Rate1 { get; set; }
public string Type2 { get; set; }
public string Break2 { get; set; }
public string Basic2 { get; set; }
public string Rate2 { get; set; }
public string Type3 { get; set; }
public string Break3 { get; set; }
public string Basic3 { get; set; }
public string Rate3 { get; set; }
}
This is my another class structure
public class RateDetail
{
public string RateType { get; set; }
public decimal Break { get; set; }
public decimal Basic { get; set; }
public decimal Rate { get; set; }
}
it has a object like below. (For easiering the understanding, I use hardcoded values and actually values assign from a csv file)
RatesInput objInput = new RatesInput();
objInput.Type1 = "T";
objInput.Break1 = 100;
objInput.Basic1 = 50;
objInput.Rate1 = 0.08;
objInput.Type2 = "T";
objInput.Break2 = 200;
objInput.Basic2 = 50;
objInput.Rate2 = 0.07;
objInput.Type3 = "T";
objInput.Break3 = 500;
objInput.Basic3 = 50;
objInput.Rate3 = 0.06;
Then I need to assign values to "RateDetail" list object like below.
List<RateDetail> lstDetails = new List<RateDetail>();
//START Looping using foreach or any looping mechanism
RateDetail obj = new RateDetail();
obj.RateType = //first iteration this should be assigned objInput.Type1, 2nd iteration objInput.Type2 etc....
obj.Break = //first iteration this should be assigned objInput.Break1 , 2nd iteration objInput.Break2 etc....
obj.Basic = //first iteration this should be assigned objInput.Basic1 , 2nd iteration objInput.Basic2 etc....
obj.Rate = //first iteration this should be assigned objInput.Rate1, 2nd iteration objInput.Rate2 etc....
lstDetails.Add(obj); //Add obj to the list
//END looping
Is there any way to convert "RatesInput" class data to "RateDetail" class like above method in C#? If yes, how to iterate data set?
Try this:
public class RatesList : IEnumerable<RateDetail>
{
public RatesList(IEnumerable<RatesInput> ratesInputList)
{
RatesInputList = ratesInputList;
}
private readonly IEnumerable<RatesInput> RatesInputList;
public IEnumerator<RateDetail> GetEnumerator()
{
foreach (var ratesInput in RatesInputList)
{
yield return new RateDetail
{
RateType = ratesInput.Type1,
Break = Convert.ToDecimal(ratesInput.Break1, new CultureInfo("en-US")),
Basic = Convert.ToDecimal(ratesInput.Basic1, new CultureInfo("en-US")),
Rate = Convert.ToDecimal(ratesInput.Rate1, new CultureInfo("en-US"))
};
yield return new RateDetail
{
RateType = ratesInput.Type2,
Break = Convert.ToDecimal(ratesInput.Break2),
Basic = Convert.ToDecimal(ratesInput.Basic2),
Rate = Convert.ToDecimal(ratesInput.Rate2, new CultureInfo("en-US"))
};
yield return new RateDetail
{
RateType = ratesInput.Type3,
Break = Convert.ToDecimal(ratesInput.Break3),
Basic = Convert.ToDecimal(ratesInput.Basic3),
Rate = Convert.ToDecimal(ratesInput.Rate3, new CultureInfo("en-US"))
};
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
And use:
var list = new RatesList(new List<RatesInput>() { objInput });
foreach (var item in list)
{
Console.WriteLine(item.Basic);
}
You can use Reflection to get the properties info like this:
var props = objInput.GetType().GetProperties();
var types = props.Where(x => x.Name.StartsWith("Type"))
.Select(x => x.GetValue(objInput)).ToList();
var breaks = props.Where(x => x.Name.StartsWith("Break"))
.Select(x => x.GetValue(objInput)).ToList();
var basics = props.Where(x => x.Name.StartsWith("Basic"))
.Select(x => x.GetValue(objInput)).ToList();
var rates = props.Where(x => x.Name.StartsWith("Rate"))
.Select(x => x.GetValue(objInput)).ToList();
List<RateDetail> lstDetails = new List<RateDetail>();
for (int i = 0; i < types.Count; i++)
{
lstDetails.Add(new RateDetail
{
RateType = types[i].ToString(),
Break = Convert.ToDecimal(breaks[i]),
Basic = Convert.ToDecimal(basics[i]),
Rate = Convert.ToDecimal(rates[i])
});
}

Get selected column from iqueryable

How can I return fieldList from an IQueryable object?
// fieldList="Code,Name";
var result = from Activity in query
select new
{
Code = Activity.Code,
Name = Activity.Name,
StatusCode = Activity.ClaimStatus.Name
};
DTO
public class CustomDto
{
public string Code { get; set; }
public string Name { get; set; }
public string StatusCode { get; set; }
}
Convert To Dto
var result = items.AsQueryable().Select(x => new CustomDto()
{
Code = x.Code,
Name = x.Name,
StatusCode = x.ClaimStatus
}).ToList();

How do I copy two similar lists?

I have two lists. There are only one field difference. How to fill the lists with each other.
[Serializable()]
public class Lst1
{
public string filed1 { get; set; }
public Int16 filed2 { get; set; }
.
.
.
public Boolean filed100 { get; set; }
}
[Serializable()]
public class Lst2
{
public string filed1 { get; set; }
public Int16 filed2 { get; set; }
.
.
.
public Boolean filed100 { get; set; }
public string filed101 { get; set; }
}
List<Lst1> Lst1_ = new List<Lst1>();
List<Lst2> Lst2_ = new List<Lst2>();
I fill out lists from files.
then,I need to fill out the list two from list one,There are many fields And I do not want to use the foreach loop.
It should be remembered that my previous class was already built and serialized and stored in a file. And now I need to transfer the previous information to the second class structure.
I do not want to use this loop!
foreach (var t in Lst1_)
{
Lst2_.Add(new lst2
{
filed1 = t.filed1,
filed2 = t.filed2,
.
.
.
filed100 = t.filed100,
filed101 = "kk"
}
}
Is this what you want?
class Lst1
{
public string filed1 { get; set; }
public string filed2 { get; set; }
public string filed3 { get; set; }
public string filed4 { get; set; }
public string filed5 { get; set; }
}
class Lst2
{
public string filed1 { get; set; }
public string filed2 { get; set; }
public string filed3 { get; set; }
public string filed4 { get; set; }
public string filed5 { get; set; }
public string filed6 { get; set; }
}
void CopyData()
{
// test data
List<Lst1> Lst1_ = new List<Lst1>()
{
new Lst1()
{
filed1 = "1",
filed2 = "2",
filed3 = "3",
filed4 = "4",
filed5 = "5",
},
new Lst1()
{
filed1 = "6",
filed2 = "7",
filed3 = "8",
filed4 = "9",
filed5 = "10",
},
};
List<Lst2> Lst2_ = new List<Lst2>();
foreach (var item in Lst1_)
{
Type type1 = item.GetType();
PropertyInfo[] properties1 = type1.GetProperties();
var current = new Lst2();
Type type2 = current.GetType();
PropertyInfo[] properties2 = type2.GetProperties();
int k = 0;
foreach (PropertyInfo property in properties1)
{
var value = property.GetValue(item, null);
int n;
bool isNumeric = int.TryParse(value.ToString(), out n);
if (!isNumeric)
value = "Your desired value";
properties2[k].SetValue(current, value);
k++;
}
Lst2_.Add(current);
}
}
It copies everything from list 1 to list2.
No need to waste your time and money, AutoMapper can do it for you with only 2 lines of code:
using AutoMapper;
namespace ConsoleApp39
{
class Program
{
static void Main (string[] args)
{
// fill list1 with data
var list1 = new List1
{
Field1 = "test",
Field2 = 5,
Field3 = false,
};
// 1) configure auto mapper
Mapper.Initialize (cfg => cfg.CreateMap<List1, List2> ());
// 2) create list2 and fill with data from list1
List2 list2 = Mapper.Map<List2> (list1);
// fill extra fields
list2.Field4 = new byte[] { 1, 2, 3 };
}
}
public class List1
{
public string Field1 { get; set; }
public int Field2 { get; set; }
public bool Field3 { get; set; }
}
public class List2
{
public string Field1 { get; set; }
public int Field2 { get; set; }
public bool Field3 { get; set; }
public byte[] Field4 { get; set; } // extra field
}
}
Do Lst1 can inheritance from Lst2?
Something like this,
the two lists:
[Serializable()]
public class Lst1
{
public string filed1 { get; set; }
public int filed2 { get; set; }
public bool filed100 { get; set; }
}
[Serializable()]
public class Lst2 : Lst1
{
public string filed101 { get; set; }
}
and one print extension
public static class CExtensions
{
public static string PropertyList(this Lst1 obj)
{
var props = obj.GetType().GetProperties();
var sb = new StringBuilder();
foreach (var p in props)
{
sb.AppendLine(p.Name + ": " + p.GetValue(obj, null));
}
return sb.ToString();
}
}
then using it:
class Program
{
static void Main(string[] args)
{
const int I = 15;
try
{
//init first list
List<Lst1> Lst1_ = new List<Lst1>();
Init(Lst1_);
//print it
Console.WriteLine("Lst1_");
Console.WriteLine(new string('-', I));
Lst1_.ForEach(x => Console.WriteLine(x.PropertyList()));
Console.WriteLine(new string('=', I));
Console.ReadKey();
//init second list
List<Lst1> Lst2_ = Lst1_.Cast<Lst1>().ToList(); //equivalent of two next lines
//List<Lst1> Lst2_ = new List<Lst2>().ConvertAll(x => (Lst1)x);
//Lst2_.AddRange(Lst1_);
//add one more
Lst2_.Add(new Lst2
{
filed1 = "101",
filed2 = 202,
filed100 = true,
filed101 = "10100"
});
//and print
Console.WriteLine("Lst2_");
Console.WriteLine(new string('-', I));
Lst2_.ForEach(x => Console.WriteLine(x.PropertyList()));
Console.WriteLine(new string('=', I));
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
}
}
private static void Init(List<Lst1> lst_)
{
for (int i = 1; i <= 3; i++)
{
lst_.Add(new Lst1
{
filed1 = i.ToString(),
filed2 = 2 * i,
filed100 = i % 2 == 0
});
}
}
}
enjoy =)

Empty data on List in LinQ Statement

I got this LinQ statement
var daysList = new List<int>(new int[30]);
var model_pdv = db_pdv.Pdv.GroupBy(x => new { Pdv = x.Clave_PDV, Nombre_Pdv = x.Nombre_Pdv})
.Select(x => new DishVM()
{
Clave_PDV = x.Key.Pdv,
Nombre_Pdv = x.Key.Nombre_Pdv,
Days = daysList,
Data = x
}).ToList();
However i dont know why my "Data" List inside my LinQ gets empty values the first time but then i saves the LinQ as it should
This is my DishVm Class:
public class DishVM
{
public string Clave_PDV { get; set; }
public string Nombre_Pdv { get; set; }
public IEnumerable<Pdv> Data { get; set; }
}
And my Pdv class:
public class Pdv
{
public string Clave_PDV { get; set; }
public string Nombre_Pdv { get; set; }
}
How can i avoid the empty Data List?
The type of x within your Select statement is IGrouping, change it to produce a list:
var model_pdv = db_pdv.Pdv.GroupBy(x => new { Pdv = x.Clave_PDV, Nombre_Pdv = x.Nombre_Pdv})
.Select(x => new DishVM()
{
Clave_PDV = x.Key.Pdv,
Nombre_Pdv = x.Key.Nombre_Pdv,
Days = daysList,
Data = x.ToList()
}).ToList();

Cannot implicitly convert type 'System.Web.Mvc.SelectList' to 'System.Collections.Generic.ICollection<System.Web.Mvc.SelectList>'

I am trying to add some values into my SelectList data member in my object but I get an error
public ActionResult Create()
{
var paf = new ProductAddForm();
paf.Sizes = new SelectList(m.GetProductSizes());
paf.Suppliers = new SelectList(m.GetAllSuppliersList(), "Id", "Name");
return View(paf);
}
that is my creat function, and the paf.Sizes / paf.Suppliers code does not work.
My productaddform class:
public class ProductAddForm
{
public double MSRP { get; set; }
public string Name { get; set; }
public string ProductId { get; set; }
public ICollection<SelectList> Sizes { get; set; }
public ICollection<SelectList> Suppliers { get; set; }
public string UPC { get; set; }
}
And my methods in my manager.cs
public IEnumerable<SupplierList> GetAllSuppliersList()
{
var fetchedObjects = ds.Suppliers.OrderBy(n => n.Name);
var Suppliers = new List<SupplierList>();
foreach (var item in fetchedObjects)
{
var s = new SupplierList();
s.Name = item.Name;
s.Id = item.Id;
Suppliers.Add(s);
}
return (Suppliers);
}
public List<string> GetProductSizes()
{
return new List<string>() { "Small", "Medium", "Large" };
}
Whats wrong?
Suppliers is a collection of SelectList. So you need to Add item into the collection
Change
paf.Suppliers = new SelectList(m.GetAllSuppliersList(), "Id", "Name");
to
paf.Suppliers.Add(new SelectList(m.GetAllSuppliersList(), "Id", "Name"));

Categories

Resources