That's my class
public class PersonelAtama
{
public int PersonelID { get; set; }
public int YonetimTalepID { get; set; }
public bool durum { get; set; }
}
I want to doDictionary<int,list<myclass>>
Dictionary<int, List<PersonelAtama>>
PersonelAtamaListesi = new Dictionary<int, List<PersonelAtama>>();
How to insert into the list
PersonelAtamaListesi.Add
How assignments are made
PersonelAtamaListesi[0][1]
PersonelAtamaListesi.Add(0,new PersonelAtama()
{
PersonelID = personelID,
YonetimTalepID = yonetimTalepID,
durum = false
});
assignment into the list and how to use again
I want to add to the list and component values to achieve. I want to sample code.
You have List as TValue so:
PersonelAtamaListesi.Add(0, new List<PersonelAtama>()
{
new PersonelAtama()
{
PersonelID = 1,
YonetimTalepID = 2,
durum = false
},
new PersonelAtama()
{
PersonelID = 11,
YonetimTalepID = 222,
durum = true
}
});
Related
I get a list using reflection and I want to fill that list with data this way :
public class SearchCriteria
{
public int SearchValue { get; set; }
public string SearchField { get; set; }
}
public class intListRequest
{
public List<SearchCriteria> SearchList { get; set; }
}
private static void ApplySearchList(intListRequest request)
{
Type type = typeof(intListRequest);
var propers = type.GetProperties();
var propsResult = propers.Where(a => a.Name == "intList");
var prop = propsResult.FirstOrDefault();
if (prop.PropertyType == typeof(List<int>))
{
List<int> newprop = prop.CastTo<List<int>>(); //**error here**//
newprop.Add(SearchValue1);
newprop.Add(SearchValue2);
newprop.Add(SearchValue3);
}
}
my problem Is with the line that I showed, how can I convert that to an int List?
I have a class showbookings with salesinformation list.
public class ShowBookings
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string ShowId { get; set; }
public DateTime ShowTime { get; set; }
public List<SalesInformation> SalesInformation { get; set; }
}
public class SalesInformation
{
public string SeatNo { get; set; }
public string SalesOrderConfirmationId { get; set; }
}
While calling update method I need to update for SeatNo and SalesOrderConfirmationId but this list is not accessible to me inside for loop.I need to return the list of items after updating showid,seatno SalesOrderConfirmationId but item.SalesInformation = salesInfo shows an error cannot convert salesinformation to generic list.Pls let me know how to sort this issue
public async Task<ActionResult<List<ShowBookings>>> UpdateShowBookings(string ShowId, string SeatNo, string SalesOrderConfirmationId)
{
var showBookings = new List<ShowBookings>();
var salesInformation = new List<SalesInformation>();
showBookings = await _context.DbCollection.Find(ShowBookings => ShowBookings.ShowId == ShowId)
.ToListAsync().ConfigureAwait(false);
if (showBookings != null)
{
var _sbList = showBookings.ToList();
foreach (var item in _sbList)
{
var salesInfo = new SalesInformation();
item.ShowId = ShowId;
salesInfo.SeatNo = SeatNo;
item.SalesInformation = salesInfo;
_sbList.Add(item);
}
return _sbList;
}
else
{
return new List<ShowBookings>();
}
}
"SalesInformation" is a list, while salesInfo is a object. You need to do:
item.SalesInformation.Add(salesInfo);
Also, in ShowBooking, inside constructor, initialize your List, else you will receive NullReferenceException.
Try to use
item.SalesInformation = new List<SalesInformation> { salesInfo };
SalesInformation of ShowBookings is List<SalesInformation> type,so you need to set its value with a list.
you already have list of showbookings
public async Task<ActionResult<List<ShowBookings>>> UpdateShowBookings(string ShowId, string SeatNo, string SalesOrderConfirmationId)
{
var salesInformation = new List<SalesInformation>();
var showBookings = await _context.DbCollection.Find(ShowBookings => ShowBookings.ShowId == ShowId)
.ToListAsync().ConfigureAwait(false);
if (showBookings != null)
{
return showBookings;
}
else
{
return new List<ShowBookings>();
}
}
I have a simple class with reference to parent object. All objects are in one list (even parent objects). Is it possible to keep references references after deserialization?
In my code I have something like this:
[ProtoContract]
public class ProtoItem
{
[ProtoMember(1)]
public int Value { get; set; }
[ProtoMember(2, AsReference = true)]
public ProtoItem BaseItem { get; set; }
}
And main looks like that:
static void Main()
{
var itemParent = new ProtoItem { Value = 1 };
var item2 = new ProtoItem { Value = 2, BaseItem = itemParent };
var item3 = new ProtoItem { Value = 3, BaseItem = itemParent };
var parentListToWrite = new List<ProtoItem> {itemParent, item2, item3};
const string file = "protofile.txt";
try { File.Delete(file); }
catch { };
using (var fs = File.OpenWrite(file)) { Serializer.Serialize(fs,
parentListToWrite); }
List<ProtoItem> readList;
using (var fs = File.OpenRead(file)) { readList =
Serializer.Deserialize<List<ProtoItem>>(fs); }
if (readList[0] == readList[2].BaseItem)
{
//how to make it equal?
}
if (readList[0] == readList[1].BaseItem)
{
//how to make it equal?
}
}
Is it possible to deserialize that if conditions works?
The protobuf specification doesn't have the notion of object identity. protobuf-net does (as an optionally enabled feature), but it doesn't currently work for list items directly, although I suspect it probably should. Since it would break the format, though, it would need explicit enabling if I fixed this.
But the following code works today - note that what I have done here is to wrap the top-level list items in a wrapper that just encapsulates the ProtoItem, but in doing so enables reference-tracking. Not ideal, but: it works.
using ProtoBuf;
using System.Collections.Generic;
using System.IO;
[ProtoContract(AsReferenceDefault=true)]
public class ProtoItem
{
[ProtoMember(1)]
public int Value { get; set; }
[ProtoMember(2)]
public ProtoItem BaseItem { get; set; }
}
[ProtoContract]
public class Wrapper
{
[ProtoMember(1, DataFormat = DataFormat.Group)]
public ProtoItem Item { get;set; }
public static implicit operator ProtoItem(Wrapper value)
{
return value == null ? null : value.Item;
}
public static implicit operator Wrapper(ProtoItem value)
{
return value == null ? null : new Wrapper { Item = value };
}
}
static class Program
{
static void Main()
{
var itemParent = new ProtoItem { Value = 1 };
var item2 = new ProtoItem { Value = 2, BaseItem = itemParent };
var item3 = new ProtoItem { Value = 3, BaseItem = itemParent };
var parentListToWrite = new List<Wrapper> { itemParent, item2, item3 };
const string file = "protofile.txt";
try
{ File.Delete(file); }
catch
{ };
using (var fs = File.OpenWrite(file))
{
Serializer.Serialize(fs,
parentListToWrite);
}
List<Wrapper> readList;
using (var fs = File.OpenRead(file))
{
readList = Serializer.Deserialize<List<Wrapper>>(fs);
}
if (readList[0].Item == readList[2].Item.BaseItem)
{
//how to make it equal?
System.Console.WriteLine("eq");
}
if (readList[0].Item == readList[1].Item.BaseItem)
{
//how to make it equal?
System.Console.WriteLine("eq");
}
}
}
Sorry for this lengthy query, I decided to add the whole test so that it will be easier for even newbies to help me with this total brain-melt.
The using directives are:
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Raven.Client;
using Raven.Client.Embedded;
using Raven.Client.Indexes;
Please leave feedback if I'm too lengthy, but what could possibly go wrong if I add a complete test?
[TestFixture]
public class ClicksByScoreAndCardTest
{
private IDocumentStore _documentStore;
[SetUp]
public void SetUp()
{
_documentStore = new EmbeddableDocumentStore {RunInMemory = true}.Initialize();
_documentStore.DatabaseCommands.DisableAllCaching();
IndexCreation.CreateIndexes(typeof (ClicksBySearchAndProductCode).Assembly, _documentStore);
}
[TearDown]
public void TearDown()
{
_documentStore.Dispose();
}
[Test]
public void ShouldCountTotalLeadsMatchingPreference()
{
var userFirst = new User {Id = "users/134"};
var userSecond = new User {Id = "users/135"};
var searchFirst = new Search(userFirst)
{
Id = "searches/24",
VisitId = "visits/63"
};
searchFirst.Result = new Result();
searchFirst.Result.Rows = new List<Row>(
new[]
{
new Row {ProductCode = "CreditCards/123", Score = 6},
new Row {ProductCode = "CreditCards/124", Score = 4}
});
var searchSecond = new Search(userSecond)
{
Id = "searches/25",
VisitId = "visits/64"
};
searchSecond.Result = new Result();
searchSecond.Result.Rows = new List<Row>(
new[]
{
new Row {ProductCode = "CreditCards/122", Score = 9},
new Row {ProductCode = "CreditCards/124", Score = 4}
});
var searches = new List<Search>
{
searchFirst,
searchSecond
};
var click = new Click
{
VisitId = "visits/64",
ProductCode = "CreditCards/122",
SearchId = "searches/25"
};
using (var session = _documentStore.OpenSession())
{
foreach (var search in searches)
{
session.Store(search);
}
session.Store(click);
session.SaveChanges();
}
IList<ClicksBySearchAndProductCode.MapReduceResult> clicksBySearchAndProductCode = null;
using (var session = _documentStore.OpenSession())
{
clicksBySearchAndProductCode = session.Query<ClicksBySearchAndProductCode.MapReduceResult>(ClicksBySearchAndProductCode.INDEX_NAME)
.Customize(x => x.WaitForNonStaleResults()).ToArray();
}
Assert.That(clicksBySearchAndProductCode.Count, Is.EqualTo(4));
var mapReduce = clicksBySearchAndProductCode
.First(x => x.SearchId.Equals("searches/25")
&& x.ProductCode.Equals("CreditCards/122"));
Assert.That(mapReduce.Clicks,
Is.EqualTo(1));
}
}
public class ClicksBySearchAndProductCode :
AbstractMultiMapIndexCreationTask
<ClicksBySearchAndProductCode.MapReduceResult>
{
public const string INDEX_NAME = "ClicksBySearchAndProductCode";
public override string IndexName
{
get { return INDEX_NAME; }
}
public class MapReduceResult
{
public string SearchId { get; set; }
public string ProductCode { get; set; }
public string Score { get; set; }
public int Clicks { get; set; }
}
public ClicksBySearchAndProductCode()
{
AddMap<Search>(
searches =>
from search in searches
from row in search.Result.Rows
select new
{
SearchId = search.Id,
ProductCode = row.ProductCode,
Score = row.Score.ToString(),
Clicks = 0
});
AddMap<Click>(
clicks =>
from click in clicks
select new
{
SearchId = click.SearchId,
ProductCode = click.ProductCode,
Score = (string)null,
Clicks = 1
});
Reduce =
results =>
from result in results
group result by
new { SearchId = result.SearchId, ProductCode = result.ProductCode }
into g
select
new
{
SearchId = g.Key.SearchId,
ProductCode = g.Key.ProductCode,
Score = g.First(x => x.Score != null).Score,
Clicks = g.Sum(x => x.Clicks)
};
}
}
public class User
{
public string Id { get; set; }
}
public class Search
{
public string Id { get; set; }
public string VisitId { get; set; }
public User User { get; set; }
private Result _result = new Result();
public Result Result
{
get { return _result; }
set { _result = value; }
}
public Search(User user)
{
User = user;
}
}
public class Result
{
private IList<Row> _rows = new List<Row>();
public IList<Row> Rows
{
get { return _rows; }
set { _rows = value; }
}
}
public class Row
{
public string ProductCode { get; set; }
public int Score { get; set; }
}
public class Click
{
public string VisitId { get; set; }
public string SearchId { get; set; }
public string ProductCode { get; set; }
}
My problem here is that I expect Count to be one in that specific test, but it just doesn't seem to add the Clicks in the Click map and the result is 0 clicks. I'm totally confused, and I'm sure that there is a really simple solution to my problem, but I just can't find it..
..hope there is a week-end warrior out there who can take me under his wings.
Yes, it was a brain-melt, for me non-trivial, but still. The proper reduce should look like this:
Reduce =
results =>
from result in results
group result by
new { SearchId = result.SearchId, ProductCode = result.ProductCode }
into g
select
new
{
SearchId = g.Key.SearchId,
ProductCode = g.Key.ProductCode,
Score = g.Select(x=>x.Score).FirstOrDefault(),
Clicks = g.Sum(x => x.Clicks)
};
Not all Maps had the Score set to a non-null-value, and therefore my original version had a problem with:
Score = g.First(x => x.Score != null).Score
Mental note, use:
Score = g.Select(x=>x.Score).FirstOrDefault()
Don't use:
Score = g.First(x => x.Score != null).Score
How to create a list dynamically from a class name (which is passed as an argument) and return the list in C#.
Below code may not work. I have posted it to give an idea:
public T ConvertDataSetToList<T>(DataSet _ds, String tableName, string className)
{
Type classType=Type.GetType(className);
List<T> newList = new List<T>();
//System.Activator.CreateInstance(Type.GetType(className));
try
{
Details _Details;
for (int iRowCount = 0; iRowCount < _ds.Tables[tableName].Rows.Count; iRowCount++)
{
_Details = FillDTO(_ds.Tables[tableName].Rows[iRowCount]);
newList.Add(_msDetails);
}
}
catch (Exception ex) { }
return newList;
}
You can dot it with some basic mapping stuff.
//Maps a dataset
public List<T> MapDataSet<T>(DataSet anyDataset
, string tablename) where T : new()
{
return MapDataTable<T>(anyDataset.Tables[tablename]);
}
// Maps a datatable
public List<T> MapDataTable<T>(DataTable table) where T : new()
{
List<T> result = new List<T>();
foreach(DataRow row in table.Rows)
{
result.Add(MapDataRow<T>(row));
}
return result;
}
// maps a DataRow to an arbitrary class (rudimentary)
public T MapDataRow<T>(DataRow row) where T: new()
{
// we map columns to class properties
Type destinationType = typeof(T);
// create our new class
T mappedTo = new T();
// iterate over the columns
for(int columnIndex=0;columnIndex<row.ItemArray.Length;columnIndex++)
{
// get a matching property of our class
PropertyInfo fieldTo = destinationType.GetProperty(
row.Table.Columns[columnIndex].ColumnName );
if (fieldTo !=null)
{
// map our fieldvalue to our property
fieldTo.SetValue(mappedTo, row[columnIndex], new object[] {});
}
else
{
// sorry, field doens't match any property on class
}
}
return mappedTo;
}
Here is basic test app to demonstrate its usage
void Main()
{
DataTable dt = new DataTable("hello");
dt.Columns.Add("foo");
dt.Columns.Add("bar");
dt.Columns.Add("foobar");
DataRow row = dt.NewRow();
row[0]="blah1";
row[1] ="two";
row[2] = "fb1";
dt.Rows.Add(row);
row = dt.NewRow();
row[0]="apples";
row[1] ="pears";
row[2] = "duh";
dt.Rows.Add(row);
List<DTO> list = MapDataTable<DTO>(dt);
List<SecondDTO> list2 = MapDataTable<SecondDTO>(dt);
}
// sample DTO object
public class DTO
{
public string foo { get; set;}
public string bar { get; set; }
}
// another sample DTO object
public class SecondDTO
{
public string foo { get; set;}
public string foobar { get; set; }
}