I am trying to write a simple Select method for a class that inherits from IList .
public class RowDataCollection : IList<RowData> { private List<RowData> rowList; internal RowDataCollection(List<RowData> data) { rowList = data; }
Some problems that I have are:
At first:
- VS2010
Cannot implicitly convert type 'IEnumerable<RowData>' to 'List<RowData>'. An explicit conversion exists (are you missing a cast?) reports Cannot implicitly convert type 'IEnumerable<RowData>' to 'List<RowData>'. An explicit conversion exists (are you missing a cast?) Cannot implicitly convert type 'IEnumerable<RowData>' to 'List<RowData>'. An explicit conversion exists (are you missing a cast?)
Alright, where does the CAST go?
Second:
- Someone might pass an invalid
colName (i.e. String.IsNullOrEmpty(colName) ) or a null parameter (object value == null) .
How can I handle the way my function returns if the input parameters are invalid?
[solvable]
I edited the Select statement (even renamed it in the sentences here). I had to use a switch to transfer to the data type that the data was in, but it works.
public RowDataCollection SelectRow(string colName, object value) { if (!String.IsNullOrEmpty(colName) && (value != null) && (0 < Rows.Count)) { switch (Rows[0][colName].GetValueType()) { case TableDataType.Boolean: return new RowDataCollection(Rows.Where(r => (bool)r[colName].Value == (bool)value).ToList()); case TableDataType.Character: return new RowDataCollection(Rows.Where(r => (char)r[colName].Value == (char)value).ToList()); case TableDataType.DateTime: return new RowDataCollection(Rows.Where(r => (DateTime)r[colName].Value == (DateTime)value).ToList()); case TableDataType.Decimal: return new RowDataCollection(Rows.Where(r => (Decimal)r[colName].Value == (Decimal)value).ToList()); case TableDataType.Integer: return new RowDataCollection(Rows.Where(r => (int)r[colName].Value == (int)value).ToList()); case TableDataType.String: return new RowDataCollection(Rows.Where(r => r[colName].Value.ToString() == value.ToString()).ToList()); } } return null; }
[Allowed (short version)]
Jon Skeet posted this around the same time that I posted my solution, and (as always) its code is much nicer.
public RowDataCollection SelectRow(string colName, object value) { List<RowData> rowList = Rows.Where(r => r[colName].Value.Equals(value)).ToList(); return new RowDataCollection(rowList); }
@Jon Skeet: If I ever see your face on the same line at some position of the software developer Iโm applying for, I'm just going to turn around and go home.
@ Total: Thanks for the help!
c # linq visual-studio-2010
jp2code
source share